def create_app(): app = Flask(__name__, static_folder='../static', static_url_path='') CORS(app) Compress(app) app.app_context().push() # 设置接口响应数据格式 app.config['JSON_AS_ASCII'] = False # 连接数据库 app.permanent_session_lifetime = datetime.timedelta(seconds=720 * 60) app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'postgresql://*****:*****@127.0.0.1:5432/island' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = False app.config['SQLALCHEMY_ECHO'] = False app.config['JWT_SECRET_KEY'] = 'UbuQgGIdry*H&&I@' app.config['JWT_BLACKLIST_ENABLED'] = False app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access', 'refresh'] db.init_app(app) db.create_all() # 注册蓝图 app.register_blueprint(auth.blueprint) # 注册JWT jwt = JWTManager(app) # Set the secret key to some random bytes. Keep this really secret! app.secret_key = b'_5#y2L"F4Q8z\n\xec]hhfhfj8989jjja/' # 日志 LoggingINFO.logging_setting() return app
def create_app(config_filename): app = Flask(__name__) app.config.from_object(config_filename) app.register_blueprint(api_bp, url_prefix='/api') with app.app_context(): db.init_app(app) db.create_all() return app
def __init__(self): # constructor which creates an instance of this class from Model import db db.drop_all() db.create_all() data = pd.read_json('interview_201909.json') df = pd.read_json(json.dumps(data[0][1]['Report'])) # this creates an instance of df and maps the column names in lowercase self.df = df.rename(columns=cols_mapper) self.engine = SQLALCHEMY_DATABASE_URI
def setUp(self): """ Test Setup """ self.app = create_app("config") self.client = self.app.test_client self.user = {'user_name': 'user_test', 'password': '******'} with self.app.app_context(): # create all tables db.create_all()
def create_app(config_filename): """ Instantiates the Flask instance and associated parameters. :params: configuration filename :return: flask app :rtype: flask object """ app = Flask(__name__) app.config.from_object(config_filename) from app import api_bp app.register_blueprint(api_bp, url_prefix='/api') from Model import db with app.app_context(): db.init_app(app) db.create_all([None]) return app
def setUp(self): app.config['TESTING'] = True app.config['CSRF_ENABLED'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'test.db') self.app = app.test_client() db.create_all()
from flask import Flask, request, session, g, redirect, url_for, \ abort, render_template, flash from flask_sqlalchemy import SQLAlchemy from sqlalchemy import not_, or_ from Model import app, db, User1, Board, Friend import md5 # configuration DATABASE = 'SNS_Database' DEBUG = True SECRET_KEY = 'development key' # create our little application :) #app = Flask(__name__) app.config.from_object(__name__) db.create_all() def session_list_renewal(): query = db.session.query(Friend.friend_email).filter(Friend.email == session['email']) user_list = db.session.query(User1.email).filter(not_(User1.email.in_(query)),User1.email != session['email']) friend_list = db.session.query(Friend.friend_email).filter(Friend.email == session['email']) post_list = db.session.query(Board).filter(or_(Board.email == session['email'],Board.email.in_(query))) session['user_list'] = user_list.all() session['friend_list'] = friend_list.all() session['post_list'] = post_list.all() @app.route('/') def index(): return render_template('index.html') @app.route('/login', methods=['GET', 'POST'])
def create_app(config_filename): app = Flask(__name__, static_folder = './public', template_folder="./static") logging.basicConfig(filename='fiplanner.log', level=logging.DEBUG, format='%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s') load_dotenv(find_dotenv()) #@app.before_first_request #def init_configs(): app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY') app.config['JWT_SECRET_KEY'] = os.environ.get('JWT_SECRET_KEY') app.config['JWT_ACCESS_TOKEN_EXPIRES'] = datetime.timedelta(days=1) app.config['JWT_BLACKLIST_ENABLED'] = True app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access', 'refresh'] app.config['JWT_TOKEN_LOCATION'] = ['cookies'] # Only allow JWT cookies to be sent over https. In production, this should likely be True app.config['JWT_COOKIE_SECURE'] = False app.config['JWT_ACCESS_COOKIE_PATH'] = '/api/' app.config['JWT_REFRESH_COOKIE_PATH'] = '/api/Token' # Twilio verify key app.config['VERIFICATION_SID'] = os.environ.get('VERIFICATION_SID') # Enable csrf double submit protection. See this for a thorough # explanation: http://www.redotheweb.com/2015/11/09/api-security.html app.config['JWT_COOKIE_CSRF_PROTECT'] = True app.config['SQLALCHEMY_ECHO'] = False app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True project_dir = os.path.dirname(os.path.abspath(__file__)) p = Path(project_dir).parents[0] database_file = "sqlite:///{}".format(os.path.join(p, "fiplanner.db")) app.config['SQLALCHEMY_DATABASE_URI'] = database_file from app import api_bp app.register_blueprint(api_bp, url_prefix='/api') from Model import db db.init_app(app) login_manager = LoginManager() login_manager.login_view = 'medium_blueprint.login' login_manager.init_app(app) jwt = JWTManager(app) # A storage engine to save revoked tokens. In production if # speed is the primary concern, redis is a good bet. blacklist = set() @jwt.token_in_blacklist_loader def check_if_token_in_blacklist(decrypted_token): jti = decrypted_token['jti'] return jti in blacklist # Create a function that will be called whenever create_access_token # is used. It will take whatever object is passed into the # create_access_token method, and lets us define what custom claims # should be added to the access token. @jwt.user_claims_loader def add_claims_to_access_token(user): try: user['user_name'] except: return {'user_name': user} return {'user_name': user['user_name']} # Create a function that will be called whenever create_access_token # is used. It will take whatever object is passed into the # create_access_token method, and lets us define what the identity # of the access token should be. @jwt.user_identity_loader def user_identity_lookup(user): try: user['user_name'] except: return {'user_name': user} return user['user_name'] # New function, verify the user claims in an access token @jwt.claims_verification_loader def verify_user_claims(user_claims): expected_keys = ['user_name'] for key in expected_keys: if key not in user_claims: return False else: checkJWT = get_jwt_identity() if(checkJWT != None): if(checkJWT['user_name'] != user_claims[key]): return False return True # New function, change the return value if user claims verification failed @jwt.claims_verification_failed_loader def failed_user_claim_verification_error(): return jsonify({'msg': 'Access token is incorrect'}), 404 @app.route('/logout', methods=['POST']) @jwt_required def logout(): jti = get_raw_jwt()['jti'] blacklist.add(jti) resp = jsonify({'logout': True}) unset_jwt_cookies(resp) return resp, 200 from Model import User, Membership @login_manager.user_loader def load_user(user_id): loaded_user = User.query.get(int(user_id)) if not loaded_user: return user_membership = Membership.query.filter_by(related_user_id=loaded_user.id).first() loaded_user.related_role_id = user_membership.related_role_id return loaded_user @app.before_request def before_request(): g.user = current_user # used to instantiate comments.db with app.app_context(): from Model import Comment from Model import Category db.create_all() db.session.commit() from templates.hello.routes import hello_blueprint from templates.medium_articles.routes import medium_blueprint # register the blueprints app.register_blueprint(hello_blueprint) app.register_blueprint(medium_blueprint) @app.before_request def block_method(): ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr) dct = dict(ip_ban_list) val = dct.get(ip) if val is not None: present = datetime.datetime.utcnow() if val > present: app.logger.warning('Blocked request from blacklist') abort(403) @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def catch_all(path): return redirect("/", code=302) return app
def db(app): _db.app = app _db.create_all() yield _db
# 用于测试User模块的功能 from flask import Flask from flask_login import UserMixin from flask_sqlalchemy import SQLAlchemy from flask_cors import CORS from werkzeug.security import generate_password_hash, check_password_hash import os from configs import IMAGEPATH from Model import db from UserControler import user_bp from AdminControler import admin_bp app = Flask(__name__) app.register_blueprint(user_bp, url_prefix='/user') app.register_blueprint(admin_bp, url_prefix='/admin') cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) app.config.from_pyfile('configs.py') app.app_context().push() db.init_app(app) # login_manager.init_app(app) if __name__ == "__main__": #在服务器上运行一次,就可以删掉了 # if not os.path.exists(IMAGEPATH): # os.makedirs(IMAGEPATH) db.create_all() app.run(debug=True)
def installer(): db.drop_all() db.create_all() return jsonify({"Success":"True","Message":"Application have been initialized successfully do not forget to make this secure or disable it after the installation"})