def setUpClass(cls): """ Set up testing flask application """ # create app cls.app = create_app(config='testing') # set test client cls.client = cls.app.test_client() # set up movies api service cls.movies_api_services_tester = MoviesAPIServices( api_base_url=cls.app.config['API_BASE_URL'], movies_endpoint=cls.app.config['API_MOVIES_ENDPOINT'], people_endpoint=cls.app.config['API_PEOPLE_ENDPOINT'], results_limit=cls.app.config['API_MAX_RESULTS']) # read test data cls.test_movies = json.load( open( os.path.dirname(os.path.abspath(__file__)) + '/test_data/test_movies.json')) cls.test_characters = json.load( open( os.path.dirname(os.path.abspath(__file__)) + '/test_data/test_characters.json'))
def main(): """ Main class for local execution. Use a proper webserver in production! """ port = int(os.getenv('PORT', '80')) app = create_app() app.run('0.0.0.0', port=port, debug=True)
def app(): db_fd, db_path = tempfile.mkstemp() app = create_app({ 'TESTING': True, 'DATABASE': db_path, }) with app.app_context(): init_db() get_db().executescript(_data_sql) yield app os.close(db_fd) os.unlink(db_path)
"""Entry point for the API.""" from init import create_app app = create_app() if __name__ == "__main__": # Locally, copy `local_settings_example.py`, remove `_example`, and set # debug mode to True. # In production, ensure debug mode is disabled. try: import local_settings debug = local_settings.DEBUG except (ImportError, AttributeError): debug = False debug = bool(debug) app.run(debug=debug)
from flask.ext.script import Manager, Server from flask.ext.assets import ManageAssets from init import create_app from init.Database import DropDatabase, CreateDatabase if __name__ == '__main__': manager = Manager(create_app()) manager.add_command('runserver', Server(host='0.0.0.0')) manager.add_command('assets', ManageAssets()) manager.add_command('dropdb', DropDatabase()) manager.add_command('createdb', CreateDatabase()) manager.run()
from flask import Flask, jsonify from flask_sqlalchemy import SQLAlchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine """ Author: Kamrul Hasan Email: [email protected] Date: 20.12.2020 """ from init import create_app app,config= create_app() db = SQLAlchemy(app) orders = db.Table(config['db_table'],db.metadata,autoload=True,autoload_with=db.engine) # automap the existing table from the database @app.route('/spend/<string:customerid>',methods=['GET']) # set the endpoint def get_orders(customerid): ''' The functions find the customer details by customerid for a GET request Parameters ---------- customerid : str The argument is used for finding the corresponding order details. Returns -------
def client(): app = create_app() app.testing = True with app.test_client() as client: yield client
""" Serve Flask App """ from waitress import serve from init import create_app # create app app = create_app(config='production') # serve app if __name__ == "__main__": try: serve(app, host='0.0.0.0', port=app.config['PORT']) except Exception as e: app.logger.error(e) raise e
def client(): """ Creates client text fixture. """ app = create_app() return app.test_client()
import os import init import json from emails import emails from flask_mail import Mail, Message from pytz import timezone eastern = pytz.timezone('US/Eastern') # URI client = MongoClient('mongodb://' + os.environ['MONGO_USER'] + ':' + os.environ['MONGO_PASSWORD'] + '@ds149905.mlab.com:49905/krispykreme') db = client.krispykreme # Set python mongo connection on environment variable app = init.create_app() mail = Mail(app) @app.route("/") def index(): return render_template("index.html") def send_messages(): print('threaded task called') with app.app_context(): print('gotten context') numbersdb = db.phone_number numbers = numbersdb.find({})
# -*-coding:utf8 -*- from flask.json import JSONEncoder as _JSONEncoder from flask import Flask as _Flask from datetime import datetime from flask_cors import CORS # ------------------------------------------ from init import create_app class JSONEncoder(_JSONEncoder): def default(self, o): if isinstance(o, datetime): return o.strftime('%Y-%m-%d') return dict(o) class Flask(_Flask): json_encoder = JSONEncoder init_app = Flask(__name__) CORS(init_app) app = create_app(init_app) if __name__ == '__main__': app.run(debug=True)
import os from flask_migrate import Migrate, MigrateCommand from flask_script import Manager, Shell from init import create_app, db app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) migrate = Migrate(app, db) def make_shell_context(): return dict(app=app, db=db) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command("db", MigrateCommand) #python3 manage.py hello --name xwq @manager.option('-n', '--name', dest='name') def hello(name): print('hello ', name) @manager.command def test(): """run the unit tests.""" import unittest tests = unittest.TestLoader().discover('tests')
from werkzeug.exceptions import HTTPException from app.http.v1.error.api import ApiException from init import create_app app = create_app(__name__) @app.errorhandler(Exception) def framework_error(e): if isinstance(e, ApiException): return e if isinstance(e, HTTPException): msg = e.description code = e.code error_code = 10001 return ApiException(msg, code, error_code) else: return ApiException()
# -*- coding: utf8 -*- from flask import Flask from werkzeug.security import generate_password_hash from models.admin import Admin from init import create_app from models import db, generate_id app = create_app(Flask(__name__)) with app.app_context(): with db.auto_commit(): # 创建一个超级管理员 user = Admin() user.account = 'super' user.password = generate_password_hash('123456') user.id = generate_id(u'超级管理员') user.auth = 2 db.session.add(user)
def test_config(): assert not create_app().testing assert create_app({'TESTING': True}).testing