This repository has been archived on 2023-05-17. You can view files and clone it, but cannot push or open issues or pull requests.
web-gpt/project/__init__.py
2023-04-17 23:28:00 +08:00

81 lines
2.5 KiB
Python

from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import yaml
import logging
import time
import traceback
# init SQLAlchemy so we can use it later in our models
db = SQLAlchemy()
def create_app():
with open("./config.yaml") as config_file:
conf = yaml.safe_load(config_file)
app = Flask(__name__)
app.config['SECRET_KEY'] = conf['app']['SECRET_KEY']
app.config['SQLALCHEMY_DATABASE_URI'] = conf['app']['SQLALCHEMY_DATABASE_URI']
app.config['HOMEPAGE_NOTICE'] = conf['app']['HOMEPAGE_NOTICE']
app.config['NETWORK_PROXY'] = conf['network']['PROXY']
app.config['OPENAI_API_KEY'] = conf['openai']['API_KEY']
app.config['OPENAI_MODEL_NAME'] = conf['openai']['MODEL_NAME']
app.config['OPENAI_PROMPT'] = conf['openai']['PROMPT']
app.config['LOGGING_LEVEL'] = conf['app']['LOGGING_LEVEL']
db.init_app(app)
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.init_app(app)
login_manager.login_message = "请先登录"
from .models import User
@login_manager.user_loader
def load_user(user_id):
# since the user_id is just the primary key of our user table, use it in the query for the user
return User.query.get(int(user_id))
with app.app_context():
db.create_all()
# blueprint for auth routes in our app
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)
# blueprint for non-auth parts of app
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
return app
app = create_app()
logger = logging.getLogger('waitress')
logger.setLevel(app.config['LOGGING_LEVEL'])
@app.before_request
def before_request():
timestamp = time.strftime('[%Y-%b-%d %H:%M]')
logger.info('%s > %s %s %s %s', timestamp, request.remote_addr,
request.method, request.scheme, request.full_path)
@app.after_request
def after_request(response):
timestamp = time.strftime('[%Y-%b-%d %H:%M]')
logger.info('%s < %s %s %s %s %s', timestamp, request.remote_addr,
request.method, request.scheme, request.full_path, response.status)
return response
@app.errorhandler(Exception)
def exceptions(e):
tb = traceback.format_exc()
timestamp = time.strftime('[%Y-%b-%d %H:%M]')
logger.error('%s %s %s %s %s 5xx INTERNAL SERVER ERROR\n%s', timestamp,
request.remote_addr, request.method, request.scheme, request.full_path, tb)
return e.status_code