https://gist.github.com/zaccrites/c5bcf96ed90907d92042
import jinja2
from flask import Flask, render_template, request, redirect, url_for
from flask.ext.sqlalchemy import SQLAlchemy from . import formatting
from .config import get_config db = SQLAlchemy() def create_app(config_name):
app = Flask(__name__)
config = get_config(config_name)
app.config.from_object(config) config.init_app(app)
db.init_app(app) register_pre_request_handlers(app)
register_post_request_handlers(app) set_error_handlers(app)
setup_logging(app)
register_blueprints(app) app.jinja_env.undefined = jinja2.StrictUndefined
setup_jinja_filters(app) return app def register_blueprints(app):
from . import general
from . import auth app.register_blueprint(general.mod)
app.register_blueprint(auth.mod) def set_error_handlers(app):
@app.errorhandler(404)
def not_found(error):
return render_template('errors/not_found.html'), 404 @app.errorhandler(403)
def forbidden(error):
return render_template('errors/forbidden.html'), 403 def register_pre_request_handlers(app):
pass def register_post_request_handlers(app):
pass def setup_jinja_filters(app):
app.jinja_env.filters['format_datetime'] = formatting.format_datetime def setup_logging(app):
if not app.debug:
import logging
from logging.handlers import RotatingFileHandler
handler = RotatingFileHandler('jmickey-blog.log', maxBytes=10000, backupCount=1)
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
import pytest
from jmickey_blog.app import create_app, db # import relevant models here @pytest.fixture
def test_app():
app = create_app('test')
with app.app_context():
db.drop_all()
db.create_all()
return app def test_some_thing():
pass def test_some_other_thing():
pass
#!/usr/bin/env python3

import sys
from jmickey_blog.app import create_app if len(sys.argv) > 1:
config_name = sys.argv[1]
else:
config_name = 'development' app = create_app(config_name) def main():
app.run() if __name__ == '__main__':
main()
https://gist.github.com/Leo-G/99dd3e1147498daade61
#!/usr/bin/env python
from flask import Flask #http://flask.pocoo.org/docs/0.10/patterns/appfactories/
def create_app(config_filename):
app = Flask(__name__)
app.config.from_pyfile(config_filename) from app.users.models import db
db.init_app(app) #Blueprints
from app.users.views import users
app.register_blueprint(users) return app app = create_app('config.py')
app.secret_key = 'some_secret'
app.debug = True
app.run
https://gist.github.com/alexanderjulo/913beb668a4f25471f2e
from flask import Flask
from celery import Celery def create_app():
app = Flask(__name__) TaskBase = celery.Task class Task(TaskBase):
"""
The usual celery base `Task` does not offer any integration into
flask, which is why we need this modified class. As the modified
class is dependent on the app, it can not just be subclassed,
but has to be dynamically created which is being taken care of
here.
"""
abstract = True def __call__(self, *args, **kwargs):
# FIXME: actually we only need app context, but flask-babel
# is broken and needs a request context
with app.test_request_context("/"):
return TaskBase.__call__(self, *args, **kwargs) celery.Task = Task
celery.conf.update(app.config)
if app.config.get('CELERY_BROKER_URL'):
celery.conf['BROKER_URL'] = app.config['CELERY_BROKER_URL']
https://gist.github.com/nejdetckenobi/6c6446b7337da9d71f4ea0580f1343c3
#!/usr/bin/env python

from __future__ import print_function

import os
import tempfile
import time import flask
import psutil
import werkzeug from saveserver import current_milli_time, intWithCommas, measure_spent_time app = flask.Flask(__name__) @app.route('/', defaults={'path': ''}, methods = ['POST'])
@app.route('/<path:path>', methods = ['POST'])
def hello(path):
app.logger.info('new request')
def custom_stream_factory(total_content_length, filename, content_type, content_length=None):
tmpfile = tempfile.NamedTemporaryFile('wb+', prefix='flaskapp')
app.logger.info("start receiving file ... filename => " + str(tmpfile.name))
return tmpfile
ms = measure_spent_time() stream,form,files = werkzeug.formparser.parse_form_data(flask.request.environ, stream_factory=custom_stream_factory)
total_size = 0 for fil in files.values():
app.logger.info(" ".join(["saved form name", fil.name, "submitted as", fil.filename, "to temporary file", fil.stream.name]))
total_size += os.path.getsize(fil.stream.name)
mb_per_s = "%.1f" % ((total_size / (1024.0*1024.0)) / ((1.0+ms(raw=True))/1000.0))
app.logger.info(" ".join([str(x) for x in ["handling POST request, spent", ms(), "ms.", mb_per_s, "MB/s.", "Number of files:", len(files.values())]]))
process = psutil.Process(os.getpid())
app.logger.info("memory usage: %.1f MiB" % (process.memory_info().rss / (1024.0*1024.0))) return "Hello World!" if __name__ == "__main__":
app.run(port=8090)
https://gist.github.com/Kevinstronger/9088662
from flask import Flask, jsonify, g, request
from sqlite3 import dbapi2 as sqlite3
DATABASE = './db/test.db'
app = Flask(__name__) def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
db.row_factory = sqlite3.Row
return db @app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None: db.close() def query_db(query, args=(), one=False):
cur = get_db().execute(query, args)
rv = cur.fetchall()
cur.close()
return (rv[0] if rv else None) if one else rv def init_db():
with app.app_context():
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit() def add_student(name='test', age=10, sex='male'):
sql = "INSERT INTO students (name, sex, age) VALUES('%s', '%s', %d)" %(name, sex, int(age))
print sql
db = get_db()
db.execute(sql)
res = db.commit()
return res def find_student(name=''):
sql = "select * from students where name = '%s' limit 1" %(name)
print sql
db = get_db()
rv = db.execute(sql)
res = rv.fetchall()
rv.close()
return res[0] @app.route('/')
def users():
return jsonify(hello='world') @app.route('/add',methods=['POST'])
def add_user():
print add_student(name=request.form['name'], age=request.form['age'], sex=request.form['sex'])
return '' @app.route('/find_user')
def find_user_by_name():
name = request.args.get('name', '')
student = find_student(name)
return jsonify(name=student['name'], age=student['age'], sex=student['sex']) if __name__ == '__main__' : app.run(debug=True)

flask factory的更多相关文章

  1. flask SQLAlchemy中一对多的关系实现

    SQLAlchemy是Python中比较优秀的orm框架,在SQLAlchemy中定义了多种数据库表的对应关系, 其中一对多是一种比较常见的关系.利用flask sqlalchemy实现一对多的关系如 ...

  2. Flask 的 Context 机制

    转自https://blog.tonyseek.com/post/the-context-mechanism-of-flask/ Flask 的 Context 机制 2014 年 07 月 21 日 ...

  3. Flask之基于route装饰器的路由系统(源码阅读解析)

    一 路由系统 1. 在flask中配置URL和视图函数的路由时,首先需要在main.py中实例化一个app对象: from flask import Flask, render_template ap ...

  4. Flask 应用最佳实践

    一个好的应用目录结构可以方便代码的管理和维护,一个好的应用管理维护方式也可以强化程序的可扩展性 应用目录结构 假定我们的应用主目录是"flask-demo",首先我们建议每个应用都 ...

  5. 基于Flask的Web应用程序插件式结构开发

    事实上,很多应用程序基于插件式结构开发,可以很方便了扩展软件的功能,并且这些功能完全可以依托于第三方开发者,只要提供好接口和完备文档,比如wordpress.谷歌火狐浏览器等. Python这样的动态 ...

  6. python flask 如何修改默认端口号

    场景:按照github文档上启动一个flask的app,默认是用5000端口,如果5000端口被占用,启动失败. 样例代码: from flask import Flask app = Flask(_ ...

  7. (转)flask的context机制

    本文转自:https://blog.tonyseek.com/post/the-context-mechanism-of-flask/ 作者:无知的 TonySeek 注意:本文仅仅作为个人mark, ...

  8. 让flask在出现语法错误时仍然自动重启

    1问题描述: flask自带的reload只能在语法没毛病的情况下auto_relaod,但是如果有语法错误,进程就会报错退出. 这时修改完语法错误,还得在控制台按“↑”和“enter”重新执行一次p ...

  9. Flask 源代码阅读笔记

    我认为我已经养成了一个坏习惯.在使用一个框架过程中对它的内部原理非常感兴趣,有时候须要花不少精力才 明确,这也导致了学习的缓慢,但换来的是对框架的内部机理的熟悉,正如侯捷所说,源代码面前,了无秘密.这 ...

随机推荐

  1. 【算法笔记】B1032 挖掘机技术哪家强

    1032 挖掘机技术哪家强 (20 分) 为了用事实说明挖掘机技术到底哪家强,PAT 组织了一场挖掘机技能大赛.现请你根据比赛结果统计出技术最强的那个学校. 输入格式: 输入在第 1 行给出不超过 1 ...

  2. 洛谷 P3332 BZOJ 3110 [ZJOI2013]K大数查询

    题目链接 洛谷 bzoj 题解 整体二分 Code #include<bits/stdc++.h> #define LL long long #define RG register usi ...

  3. ssm裤架搭建异常: Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService' ...

  4. springLdap 操作ldap示例(增删改查)

    转自:http://blog.csdn.net/sundenskyqq/article/details/9002440 这部分的示例网上的确有很多,但是个人在查找的过程中还是感到不够满意,所以就自己总 ...

  5. sqlmap命令小结

    --technique 这个参数可以指定sqlmap使用的探测技术,默认情况下会测试所有的方式. 支持的探测方式如下: B: Boolean-based blind SQL injection(布尔型 ...

  6. python学习11-类的成员(转载)

    一.变量 1.实例变量(又叫字段.属性) 创建对象时给对象赋值 形式: self.xxx = xxx 访问: 对象名.xxx     只能由对象访问 class Person: def __init_ ...

  7. Python学习 day04

    一.list list可以存放各种类型的数据,与java中list类差不多,比如li = ['keith', 1, True, [1, 2, 3], {name: 'tangtang', age: 1 ...

  8. Charts in Ionic

    Chart对于任何应用来说都是不可或缺的一部分,hybrid app也是如此. 先罗列一下有哪些可用的Chart library: D3.JS -- Data-Driven Documents,BSD ...

  9. andoid 多线程断点下载

    本示例介绍在Android平台下通过HTTP协议实现断点续传下载. 我们编写的是Andorid的HTTP协议多线程断点下载应用程序.直接使用单线程下载HTTP文件对我们来说是一件非常简单的事.那么,多 ...

  10. React.js 小书 Lesson12 - state vs props

    作者:胡子大哈 原文链接:http://huziketang.com/books/react/lesson12 转载请注明出处,保留原文链接和作者信息. 我们来一个关于 state 和 props 的 ...