flask factory
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的更多相关文章
- flask SQLAlchemy中一对多的关系实现
SQLAlchemy是Python中比较优秀的orm框架,在SQLAlchemy中定义了多种数据库表的对应关系, 其中一对多是一种比较常见的关系.利用flask sqlalchemy实现一对多的关系如 ...
- Flask 的 Context 机制
转自https://blog.tonyseek.com/post/the-context-mechanism-of-flask/ Flask 的 Context 机制 2014 年 07 月 21 日 ...
- Flask之基于route装饰器的路由系统(源码阅读解析)
一 路由系统 1. 在flask中配置URL和视图函数的路由时,首先需要在main.py中实例化一个app对象: from flask import Flask, render_template ap ...
- Flask 应用最佳实践
一个好的应用目录结构可以方便代码的管理和维护,一个好的应用管理维护方式也可以强化程序的可扩展性 应用目录结构 假定我们的应用主目录是"flask-demo",首先我们建议每个应用都 ...
- 基于Flask的Web应用程序插件式结构开发
事实上,很多应用程序基于插件式结构开发,可以很方便了扩展软件的功能,并且这些功能完全可以依托于第三方开发者,只要提供好接口和完备文档,比如wordpress.谷歌火狐浏览器等. Python这样的动态 ...
- python flask 如何修改默认端口号
场景:按照github文档上启动一个flask的app,默认是用5000端口,如果5000端口被占用,启动失败. 样例代码: from flask import Flask app = Flask(_ ...
- (转)flask的context机制
本文转自:https://blog.tonyseek.com/post/the-context-mechanism-of-flask/ 作者:无知的 TonySeek 注意:本文仅仅作为个人mark, ...
- 让flask在出现语法错误时仍然自动重启
1问题描述: flask自带的reload只能在语法没毛病的情况下auto_relaod,但是如果有语法错误,进程就会报错退出. 这时修改完语法错误,还得在控制台按“↑”和“enter”重新执行一次p ...
- Flask 源代码阅读笔记
我认为我已经养成了一个坏习惯.在使用一个框架过程中对它的内部原理非常感兴趣,有时候须要花不少精力才 明确,这也导致了学习的缓慢,但换来的是对框架的内部机理的熟悉,正如侯捷所说,源代码面前,了无秘密.这 ...
随机推荐
- 通过 rundll32 创建设置注册表项权限
[Version]SIGNATURE="$Windows NT$" [DefaultInstall]AddReg=test.reg [test.reg]HKLM,"SOF ...
- ThinkPHP5.0的助手函数汇总
load_trait:快速导入Traits,PHP5.5以上无需调用 /** * 快速导入Traits PHP5.5以上无需调用 * @param string $class trait库 * @pa ...
- phpcms V9 框架目录结构
phpcms v9框架的目录结构分析: 了解v9框架的目录结构,有助于帮助我们快速建立起对v9框架的一个整体认识 打开"mycms"项目,有如下文件和目录 使用 ...
- if __name__ == '__main__' 详解
1.__name__是啥 __name__ 是Python的模块名字. 手册解释:The name of the module. 2.__name__的值 首先,一个变量一次只有一个值. 其次,__n ...
- jquery将日期转换成指定格式的字符串
引用jquery文件,如<script type="text/javascript" src="jquery-1.8.3.min.js"></ ...
- Quartz.NET 作业调度使用
Quartz.NET的使用方法有很多,今天使用Quartz.NET3.0.6的时候发现和2.0版本的语法不太一样,百度上找了一圈也没有找到解决办法 后来在GitHub上下载源代码解决了 实现每隔10s ...
- journalctl 中文手册
版权声明 本文译者是一位开源理念的坚定支持者,所以本文虽然不是软件,但是遵照开源的精神发布. 无担保:本文译者不保证译文内容准确无误,亦不承担任何由于使用此文档所导致的损失. 自由使用:任何人都可以自 ...
- Docker的镜像迁移
[root@localhost ~]# mkdir /opt/soft/ [root@localhost ~]# docker save c3987965c15d > /opt/soft/pos ...
- TOJ 2888 Pearls
Description In Pearlania everybody is fond of pearls. One company, called The Royal Pearl, produces ...
- [ElasticSearch] 如何使用中文分詞ik與繁簡轉換stconvert插件
一. 環境安裝 ElasticSearch(以下簡稱ES)安裝已經算相對簡單了, 但要使用需要配置的插件, 對剛入門的新手還是有點麻煩, 所幸medcl大神提供一個配置好的ES-rtf版本, 新手們在 ...