flask的安装与使用

说明

最近的项目需要用到flask,貌似3年前用过,不过很久没搞了
以前java web比较熟。这里做个简单的入门记录

官网:
http://docs.jinkan.org/docs/flask/

下载与安装

pip install flask
建议用virtualenv

一个例子

flask的安装与使用_第1张图片

from flask import Flask

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello World!'


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

例子2

带参数

@app.route('/user/')
def show_user_profile(username):
    # show the user profile for that user
    return 'User %s' % username

@app.route('/post/')
def show_post(post_id):
    # show the post with the given id, the id is an integer
    return 'Post %d' % post_id

访问:
http://127.0.0.1:5000/post/122

http://127.0.0.1:5000/user/jjjjj

一个简易登陆逻辑

三个文件 :

flask的安装与使用_第2张图片
效果示意:
flask的安装与使用_第3张图片

index.html





    
    
        首页
    




{% if uname %} 登出 {% else %} 登陆 {% endif %}
{% if uname %}

Hello {{ uname }}!

{% else %}

你没有登陆,请先登陆!

{% endif %}

login.html





    
    
        登录
    




登录

app.py

from flask import Flask, escape, request, session, redirect, url_for,render_template

app = Flask(__name__)
app.secret_key = "123456"

@app.route('/')
def hello_world():
    return redirect(url_for('index'))


@app.route('/index')
def index():
    if 'uname' in session:
        uname = session['uname']
        return render_template('index.html', uname=uname)
    else:
        return render_template('index.html')


@app.route('/login_page')
def login_page():
    return render_template('login.html')

@app.route('/logout')
def logout():
     session.clear()
     return redirect(url_for('index'))


@app.route('/login', methods=['GET', 'POST'])
def login():
    # 判空
    if (not 'uname' in  request.form) or not ( 'pwd' in  request.form):
        errmsg = "uname and pwd can not be null"
        print(errmsg)
        return errmsg

    uname = request.form['uname']
    pwd = request.form['pwd']
    # 判断 method
    if request.method == 'POST':
        print("yes,post")
    else:
        errmsg = "no,method is wrong," + request.method
        print(errmsg)
        return errmsg

    if uname == 'dgm' and pwd == '123456':
        # 放到session中
        # 这一行可能 会抛,The session is unavailable because no secret ,需要增加 app.secret_key = "123456" 这样的配置
        session['uname'] = uname
        return redirect(url_for('index'))
    else:
        return "wrong uname or pwd"



if __name__ == '__main__':
    # app.run()
    app.run(debug=True)


app.py的说明

@app.route(’/’) 进首页跳到index

@app.route(’/index’) 为首页, session中有用户则显示 用户,无用户则提示用户登陆

@app.route(’/login_page’) 进登陆界面

@app.route(’/logout’) 登出请求,把session给清空

@app.route(’/login’, methods=[‘GET’, ‘POST’]) 登陆提交,成功则进index

filter或拦截器之类

可以用
before_request,after_request

如:


@app.before_request
def print_request_info():
    print("请求地址:" + str(request.path))
    print("请求方法:" + str(request.method))
    print("---请求headers--start--")
    print(str(request.headers).rstrip())
    print("---请求headers--end----")
    print("GET参数:" + str(request.args))
    print("POST参数:" + str(request.form))

每次请求都会打印 上面的内容

把路由的内容分到多个文件

我们现在是把 route都加到了app.js,如果 业务变得很多这个内容就会很大,不好维护,所以我们需要多个文件来拆分,使用flask的 blueprint 模块

我们还是用之前的逻辑,
但尝试把 下面三个请求 扔到 auth.js中,
@app.route(’/login_page’)
@app.route(’/logout’)
@app.route(’/login’, methods=[‘GET’, ‘POST’])

[外链图片转存失败(img-25mITl06-1568452641771)(en-resource://database/3157:0)]

auth.py :

from flask import Flask, escape, request, session, redirect, url_for,render_template,Blueprint

mod = Blueprint('auth',__name__)


@mod.route('/login_page')
def login_page():
    return render_template('login.html')

@mod.route('/logout')
def logout():
     session.clear()
     return redirect(url_for('index'))

@mod.route('/login', methods=['GET', 'POST'])
def login():
    # 判空
    if (not 'uname' in  request.form) or not ( 'pwd' in  request.form):
        errmsg = "uname and pwd can not be null"
        print(errmsg)
        return errmsg

    uname = request.form['uname']
    pwd = request.form['pwd']
    # 判断 method
    if request.method == 'POST':
        print("yes,post")
    else:
        errmsg = "no,method is wrong," + request.method
        print(errmsg)
        return errmsg

    if uname == 'dgm' and pwd == '123456':
        # 放到session中
        # 这一行可能 会抛,The session is unavailable because no secret ,需要增加 app.secret_key = "123456" 这样的配置
        session['uname'] = uname
        return redirect(url_for('index'))
    else:
        return "wrong uname or pwd"

app.py 有变化:

from flask import Flask, escape, request, session, redirect, url_for,render_template
from views import auth

app = Flask(__name__)
app.secret_key = "123456"
app.register_blueprint(auth.mod,url_prefix='/')

@app.route('/')
def hello_world():
    return redirect(url_for('index'))


@app.route('/index')
def index():
    if 'uname' in session:
        uname = session['uname']
        return render_template('index.html', uname=uname)
    else:
        return render_template('index.html')

if __name__ == '__main__':
    # app.run()
    app.run(debug=True)

留意上面的 app.register_blueprint(auth.mod,url_prefix=’/’),即把其它模块的 路由加上.
其它不变.

你可能感兴趣的:(web,python)