Beispiel #1
0
def create_app():
    app = Flask(__name__)
    #密钥
    app.config["SECRET_KEY"] = "shibushishayawoshelemiyao"


    #指定session存储方案
    app.config["SESSION_TYPE"]="redis"
    #设置缓存开头,一般以自己pythonpoackage的app名字为开头
    app.config["SESSION_KEY_PREFIX"] = "myapp"
    # 定制化的将session存在redis的指定库中
    app.config["SESSION_REDIS"] = StrictRedis(host="127.0.0.1", db=5)


    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    #创建数据库文件
    # app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///sqlite3.db"
    app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:[email protected]:3306/flask02"

    #实例化第三方插件
    #实例化Session
    sess = Session()
    sess.init_app(app)
    db.init_app(app)

    app.register_blueprint(blue)
    return app
Beispiel #2
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    db.init_app(app)
    login_manager.init_app(app)

    from myapp.api import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api')

    return app
Beispiel #3
0
def create_app(config={}):
    app = Flask(__name__)
    app.config.from_object('myapp.config_dev')
    app.config.update(config)

    db.init_app(app)
    lm.init_app(app)
    # app.debug = True
    app = register_web_views(app)
    app = register_api_views(app)
    Bootstrap(app)

    return app
Beispiel #4
0
def create_app(config_object):
    app = Flask(__name__)
    app.config.from_object(config_object)
    db.init_app(app)
    ma.init_app(app)
    migrate = Migrate(app, db)
    login_manager = LoginManager()
    login_manager.init_app(app)

    app.jinja_env.globals.update(__builtins__)
    app.register_blueprint(short_link_blueprint)

    @login_manager.user_loader
    def load_user(id):
        return User.query.get(int(id))

    @app.route("/")
    def index():
        return render_template("index.html")

    @app.route("/<string:link>")
    def redirect_to_long_url(link):
        url_shortener = URLShortener()
        # In case that link contains unsupported by url_shortener chars
        try:
            long_url_id = url_shortener.decode(link)
        except ValueError:
            abort(404, f"This short link is not valid")

        long_url_db_entry = ShortUrl.query.filter_by(id=long_url_id).first()
        if not long_url_db_entry:
            abort(404, f"This short link is not valid")
        long_url = long_url_db_entry.long_url

        # Just in case
        # Its good practise to check data on entry and exit
        if not validators.url(long_url):
            abort(404, f"This long url is not a valid URL!")

        # On click increase number of Clicks
        long_url_db_entry.clicks.number_of_clicks += 1
        db.session.commit()

        return redirect(long_url)

    @app.route("/admin_login", methods=["GET", "POST"])
    def login_for_admin():
        #print(f"Referer - {request.referrer}")
        if current_user.is_authenticated:
            flash("You are already logged in!")
            # NO redirect to referer, coz there is no referer
            return redirect(url_for("index"))

        login_form = LoginForm()
        if login_form.validate_on_submit():
            user = User.query.filter_by(username=login_form.username.data).first()
            if user and user.check_password(password=login_form.password.data):
                login_user(user, remember=True)
                flash("You are now logged in!")
                # NO redirect to referer, coz there is no referer
                return redirect(url_for("index"))
            else:
                flash("Invalid username or password")
                return redirect(url_for("login_for_admin"))
        return render_template("login.html", form=login_form)

    @app.route("/admin")
    @login_required
    def admin_view():
        links = (
            ShortUrl.query.join(ShortUrl.clicks)
            .order_by(db.desc(Click.number_of_clicks))
            .limit(10)
            .all()
        )
        return render_template("admin.html", links=links)

    @app.route("/logout")
    @login_required
    def logout():
        logout_user()
        flash("You are now logged out!")
        return redirect(url_for("index"))

    @app.errorhandler(404)
    def not_found(error):
        return render_template("404.html"), 404

    @app.errorhandler(500)
    def internal_error(error):
        db.session.rollback()
        return render_template('500.html'), 500

    return app
Beispiel #5
0
from myapp.utils import get_instance_folder_path
from myapp.api_routes import *
from myapp.config import configure_app
from myapp.models import db

###############################################################################

# Initialise
#############

app = Flask(__name__,
            instance_path=get_instance_folder_path(),
            instance_relative_config=True)

configure_app(app)  # load configurations
db.init_app(app)  # init app to db

###############################################################################

# Error Handling
#################


@app.errorhandler(404)
def page_not_found(error):
    app.logger.error('Page not found: %s', (request.path, error))
    return "404"


@app.errorhandler(500)
def internal_server_error(error):
Beispiel #6
0
from flask import Flask
from myapp.models import db
# 重点关注py2与py3的import区别,相对路径与绝对路径
# python2缺省为相对路径导入,python3缺省为绝对路径导入,python2缺省会搜索上一级目录、上上级目录
# from .views.simple_page import simple_page  #py2 from .views.simple_page import simple_page
#                                              # ValueError: Attempted relative import in non-package
# from views.simple_page import simple_page  #py2 from ..models import db
#                                             # ValueError: Attempted relative import beyond toplevel package

from myapp.views.simple_page import simple_page  # py2 ok!
from myapp.views.simple_view import simple_view  # py3 ok!

print("__name__", __name__)
app = Flask(__name__)
app.config.from_pyfile('config.py')
app.register_blueprint(simple_page, url_prefix='/pages')
app.register_blueprint(simple_view, url_prefix='/views')

db.init_app(app)


@app.teardown_request
def shutdown_session(exception=None):
    db.session.remove()


if __name__ == '__main__':
    print(vars(app))
    app.run()