import os import unittest from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from app import blueprint from app.main import create_app, db app = create_app(os.getenv("FLASK_ENV") or "dev") app.register_blueprint(blueprint) app.app_context().push() manager = Manager(app) migrate = Migrate(app, db) manager.add_command("db", MigrateCommand) @manager.command def run(): app.run() @manager.command def test(): """Runs the unit tests.""" tests = unittest.TestLoader().discover("app/test", pattern="test*.py") result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): return 0 return 1
""" Descrição do arquivo: este é o arquivo principal da API, aqui será feito o gerenciamento do banco de dados (com os comandos drop_db e create_db, por exemplo) e a execução da API (com o comando run) Imports deste arquivo: Manager: permite criar comandos para usar na linha de comando com o decorator @manager.command create_app: cria o app já com o db setado (ver em app/main/__init__.py) db: objeto SQAlchemy para o gerenciamento do banco de dados através do Flask blueprint: objeto que registra informações a respeito das funções da API (útil para a modularização) """ from flask_script import Manager from app.main import create_app, db from app import blueprint app = create_app() app.register_blueprint(blueprint) # liga o contexto do 'app' ao contexto atual do script app.app_context().push() manager = Manager(app) @manager.command def run(): """Run the API""" app.run(debug=True, host='0.0.0.0', port=5000) @manager.command def drop_db():
import os import unittest from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from app import blueprint from app.main import create_app,db from app.main.model import user,blacklist app = create_app(os.getenv('BOILERPLATE_ENV') or 'dev') app.register_blueprint(blueprint) app.app_context().push() manager = Manager(app) migrate = Migrate(app,db) manager.add_command('db',MigrateCommand) @manager.command def run(): app.run(host='0.0.0.0') @manager.command def test(): tests = unittest.TestLoader().discover('app/test',pattern='test*.py') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful():
import os import unittest from flask_migrate import Migrate, MigrateCommand from app import blueprint from app.main import create_app, db from app.main.model import user, blacklist app = create_app(os.getenv('FLASK_ENV') or 'development') app.register_blueprint(blueprint) app.app_context().push() migrate = Migrate(app, db) @app.cli.command("run") def run(): app.run() @app.cli.command("test") def test(): """Runs the unit tests.""" tests = unittest.TestLoader().discover('app/test', pattern='test*.py') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): return 0 return 1 if __name__ == '__main__':
def main(): """PGSync Demo Webserver.""" app = create_app() web.run_app(app)
def test_get_all_api(): app = create_app() with app.test_client() as c: rv = c.get('/person/') assert rv.status_code == 200
import os import unittest from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from app.main import create_app, db from app import blueprint app = create_app(os.getenv('BOILERPLATE_ENV') or 'prod') app.register_blueprint(blueprint) app.app_context().push() manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) @app.after_request def after_request(response): """ Allows response resources to be shared with the given source. """ response.headers.add('Access-Control-Allow-Origin', '*') return response
import os from app import blueprint from app.main import create_app application = create_app(os.getenv('EXEC_ENV') or 'dev') application.register_blueprint(blueprint) application.app_context().push() if __name__ == '__main__': application.run()
from app.main.message import MessageStoreError from db import init_db from flask import g, request, session, make_response, jsonify from app.main import create_app from app.logic import message_service as ms from app.logic import user_service as us import os import tempfile app = create_app(__name__) app.secret_key = b'_5#y2L"F4Q8z\n\xec]/' def create_db_file(): """ :rtype: str :return: """ temp_db_path = tempfile.NamedTemporaryFile().name app.logger.info('Database path: {0}'.format(temp_db_path)) return temp_db_path db_path = create_db_file() app.config['DATABASE'] = db_path with app.app_context(): init_db() # Post Create message
from flask_script import Manager from app import blueprint from app.main import create_app, db app = create_app('prod') app.register_blueprint(blueprint) app.app_context().push() manager = Manager(app) @manager.command def run(): app.run() if __name__ == '__main__': manager.run()
import os import unittest from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from app.main import (create_app, db) # importing our app from app import blueprint # importing services from app.main.models import * # importing all our db models for migrations app = create_app(os.getenv('FLASK_ENV') or 'dev') # dev, prod or test app.register_blueprint(blueprint) # registering in Flask application instance app.app_context().push() # Instantiates the manager and migrate classes # by passing the app instance to their respective # constructors manager = Manager(app) migrate = Migrate(app, db) # Exposing all the database migration commands # through Flask-Script manager.add_command('db', MigrateCommand) @manager.command def run(): app.run(host='0.0.0.0', port=5000) # host exposed (works with docker) @manager.command def test(): """Runs the unit tests""" tests = unittest.TestLoader().discover('app/test', pattern='test*.py')
def client(): _client = TestClient(create_app()) yield _client
import os import unittest from flask_script import Manager from app.main import create_app from app.main.controller.company_controller import CompanyService from app.main.controller.member_controller import MemberService from app.main.controller.team_controller import TeamService app = create_app(os.getenv('ENV_STATE')) app.app_context().push() manager = Manager(app) app.register_blueprint(CompanyService) app.register_blueprint(MemberService) app.register_blueprint(TeamService) @manager.command def run(): app.run(port=5000, host="0.0.0.0") @manager.command def test(): """Runs the unit tests.""" tests = unittest.TestLoader().discover('app/test', pattern='test*.py') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): return 0 return 1
import datetime from flask import jsonify from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from app import blueprint from app.main import create_app, db, socketio from app.main.model import user, message, game, room, game_user, room_user, follower_user from app.main.model.game import Game from app.main.model.user import User from flask_cors import CORS app = create_app(os.getenv('APP_ENV') or 'development') def init_db(): # create new game when run app battle_ship = Game.query.filter_by(public_id="battle_ship").first() if battle_ship is None: battle_ship = Game(public_id="battle_ship", name="Battle Ship", num_players=2) db.session.add(battle_ship) db.session.commit() # create admin account when run app admin = User.query.filter_by(public_id="admin").first()
import os from app.main import create_app def _get_words(): result = [] with open('words.txt') as file: for word in file: result.append(word.strip()) return result PORT = 5000 if __name__ == '__main__': port = int(os.environ.get('PORT', PORT)) app = create_app(_get_words()) app.run(host='0.0.0.0', port=port)
import os import unittest from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from app.main import create_app, db from app.main.model import user from app.main.model import blacklist from app import blueprint app = create_app(os.getenv("ENV")) app.register_blueprint(blueprint) app.app_context().push() manager = Manager(app) migrate = Migrate(app, db) manager.add_command("db", MigrateCommand) @manager.command def run(): app.run() @manager.command def test(): tests = unittest.TestLoader().discover("app/test", pattern="test*.py")
import os import unittest from app import blueprint from flask_cors import CORS from app.main import create_app from flask_script import Manager from flask_jwt_extended import JWTManager app = create_app(os.getenv('ENV') or 'DEV', is_test=False) # app = create_app(os.getenv('ENV') or 'TEST', is_test=True) app.register_blueprint(blueprint) app.app_context().push() jwt = JWTManager(app) manager = Manager(app) # CORS(app) # app.run() CORS(app, resources={r"/*": {"origins": "*"}}) @manager.command def test(): """Runs the unit tests.""" tests = unittest.TestLoader().discover('app/test', pattern='test*.py') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): return 0 return 1 # test() if __name__ == '__main__': app.run(debug=True)
def test_get_api(): app = create_app() client = app.test_client() res = client.get('/person/') assert res.status_code == 200
def test_get_one_api(mock_ps): app = create_app() mock_ps.return_value.retrieve_one.return_value = Person(name='wrong', primary_email='ncwk') with app.test_client() as c: rv = c.get('/person/123') assert rv.status_code == 200
def test_create_api(): app = create_app() client = app.test_client() res = client.post('/person/', json={"name": "gandhi", "email": "*****@*****.**"}) assert res.status_code == 202
def test_when_app_is_created_then_corpus_is_populated_with_english_dictionary(): app = create_app(['dear', 'dare']) with app.test_client() as test_client: response = test_client.get('/anagrams/dear.json') response_string = response.get_data().decode() assert ['dare'] == sorted(json.loads(response_string)['anagrams'])
import os from app.main import config from app.main import create_app config = config.ProdConfig if "prod" == os.getenv( "FLASK_ENV") else config.DevConfig app = create_app(config) if __name__ == "__main__": app.run(host='0.0.0.0')
import os import unittest from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from app.main import create_app, db from app.main.model import user, blacklist from app import blueprint app = create_app(os.getenv('APP_ENV') or 'dev') app.register_blueprint(blueprint) app.app_context().push() manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) app.app_context().push() @manager.command def run(): app.run() @manager.command def test(): tests = unittest.TestLoader().discover('app/test', pattern='test*.py') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): return 0 return 1
import os import unittest from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from app import blueprint from app.main import create_app, db from app.main.model import user, book, blacklist app = create_app(os.getenv('FLASKBOOKSTORE_ENV') or 'dev') app.register_blueprint(blueprint) app.app_context().push() manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) @manager.command def run(): app.run() @manager.command def test(): tests = unittest.TestLoader().discover('app/test', pattern='test*.py') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful():
async def test_method_not_allowed(aiohttp_client): client = await aiohttp_client(create_app()) res = await client.post("/logout", data={"some": "data"}) assert res.status == 405
import os from flask_script import Manager from app import blueprint import app from app.main import create_app app = create_app(os.getenv('UPDRAFT_ENV') or 'dev') app.register_blueprint(blueprint) app.app_context().push() manager = Manager(app) @manager.command def run(): app.run() if __name__ == '__main__': manager.run()
import os import unittest from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from app import blueprint from app.main import create_app, db from app.main.model import user, blacklist app = create_app(os.getenv('CONFIG') or 'dev') app.register_blueprint(blueprint) app.app_context().push() manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) @manager.command def setupdb(): db.create_all() db.session.commit() @manager.command def run(): if os.getenv('CONFIG') == "dev": app.config.from_object('app.main.config.DevelopmentConfig') else: app.config.from_object('app.main.config.ProductionConfig')
import os import unittest from flask_script import Manager from app.main import create_app from app import blueprint env = os.getenv('BOILERPLATE_ENV') or 'dev' app = create_app(env) app.register_blueprint(blueprint) app.app_context().push() manager = Manager(app) @manager.command def run(): app.run() @manager.command def test(): """Runs the unit tests.""" tests = unittest.TestLoader().discover('app/test', pattern='test*.py') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): return 0 return 1
import os import unittest from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from app.main import create_app, db from app.main.model import user from app import blueprint app = create_app(os.getenv('TODO_ENV') or 'dev') app.register_blueprint(blueprint) app.app_context().push() manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) @manager.command def run(): app.run(host='0.0.0.0', port=8080) @manager.command def test(): """Runs the unit tests.""" tests = unittest.TestLoader().discover('app/test', pattern='test*.py')
def test_post_api(user): app = create_app() with app.test_client() as c: rv = c.post('/person/', json=user) assert rv.status_code == 202
import os import unittest import pymysql pymysql.install_as_MySQLdb() from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from app.main.model import todo from app.main import create_app, db from app import blueprint from flask_cors import CORS app = create_app('dev') CORS(app) app.register_blueprint(blueprint) app.app_context().push() # flask_script : https://flask-script.readthedocs.io/en/latest/ manager = Manager(app) # flask_migrate : https://flask-migrate.readthedocs.io/en/latest/ migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) @manager.command def run(): app.run() @manager.command
def test_post_api_in_valid_payload(user): app = create_app() with app.test_client() as c: rv = c.post('/person/', json={'xyz': 123}) assert rv.status_code == 422
def app(): return create_app([])
# -*- coding: utf-8 -*- from app.main import create_app application = None # Create application object for debugging or production. # http://pythonhosted.org/Flask-SQLAlchemy/contexts.html if __name__ == '__main__': from flask.ext.script import Manager from flask.ext.assets import ManageAssets from flask.ext.migrate import Migrate, MigrateCommand from app.shared.models import db from app.assets import assets_env from app.util import GenerateSitemap application = create_app(debug=True) application.test_request_context().push() # This 'migrate' instance is required by MigrateCommand. migrate = Migrate(application, db) manager = Manager(application) manager.add_command('db', MigrateCommand) manager.add_command('assets', ManageAssets(assets_env)) manager.add_command('sitemap', GenerateSitemap(application.static_folder)) manager.run() else: application = create_app(debug=False)