Last active
September 7, 2019 01:39
-
-
Save frostming/b951a23d1fba6393aae0acef38599147 to your computer and use it in GitHub Desktop.
Simple Flask APP with Dispatcher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import flask | |
from flask_login import LoginManager, UserMixin, login_user, logout_user | |
from flask_sqlalchemy import SQLAlchemy | |
from werkzeug.middleware.dispatcher import DispatcherMiddleware | |
settings = { | |
"SECRET_KEY": "hesdfdsfklj;l", | |
"SQLALCHEMY_DATABASE_URI": "sqlite:///db.sqlite3", | |
} | |
db = SQLAlchemy() | |
login_manager = LoginManager() | |
class User(UserMixin, db.Model): | |
id = db.Column(db.Integer, primary_key=True) | |
name = db.Column(db.String(20), default="admin") | |
@login_manager.user_loader | |
def get_user(id): | |
return User.query.get(id) | |
def index(): | |
return flask.render_template("page.html") | |
def login(): | |
user = User.query.first() | |
login_user(user) | |
return flask.redirect(flask.url_for("index")) | |
def logout(): | |
logout_user() | |
return flask.redirect(flask.url_for("index")) | |
def create_app(name="default"): | |
app = flask.Flask(__name__) | |
app.config.from_mapping(settings, NAME=name) | |
db.init_app(app) | |
login_manager.init_app(app) | |
app.add_url_rule("/login", "login", login) | |
app.add_url_rule("/logout", "logout", logout) | |
app.add_url_rule("/index", "index", index) | |
@app.cli.command() | |
def initdb(): | |
db.create_all() | |
db.session.add(User()) | |
db.session.commit() | |
return app | |
application = create_app() | |
application.wsgi_app = DispatcherMiddleware( | |
application.wsgi_app, {"/foo": create_app("foo"), "/bar": create_app("bar")} | |
) | |
if __name__ == "__main__": | |
application.run() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment