Flask

简介

Flask是一个使用 Python 编写的轻量级 Web 应用框架。其 WSGI 工具箱采用 Werkzeug ,模板引擎则使用 Jinja2 。Flask使用 BSD 授权。

Hello World

from flask import Flask
 app = Flask(__name__)
 @app.route('/')
 def hello_world():
     return 'Hello World'
 if __name__ == '__main__':
     app.run()

路由规则

from flask import Flask
 app = Flask(__name__)
 @app.route('/hello/<name>')
 def hello_name(name):
     return 'Hello %s!' % name
 if __name__ == '__main__':
     app.run(debug = True)
from flask import Flask
 app = Flask(__name__)
 @app.route('/blog/<int:postID>')
 def show_blog(postID):
     return 'Blog Number %d' % postID
 @app.route('/rev/<float:revNo>')
 def revision(revNo):
     return 'Revision Number %f' % revNo
 if __name__ == '__main__':
     app.run()
from flask import Flask, redirect, url_for, request
 app = Flask(__name__)
 @app.route('/success/<name>')
 def success(name):
     return 'welcome %s' % name
 @app.route('/login',methods = ['POST', 'GET'])
 def login():
     if request.method == 'POST':
         user = request.form['name']
         return redirect(url_for('success',name = user))
     else:
         user = request.args.get('name')
         return redirect(url_for('success',name = user))
 if __name__ == '__main__':
     app.run(debug = True)
@app.route('/')
def hello_world():  # put application's code here
    return flask.render_template("index.html")
@app.route('/search',methods = ['POST', 'GET'])
def search():  # put application's code here
    linkstr="q="
    if request.method == 'POST':
        stars = request.form.get('stars')
        owners = request.form.get('owners')
        language = request.form.get('language')
        license = request.form.get('license')
        date=request.form.get('date')
    if request.method == 'GET':
        owners = None
        language = None
        license = None
        date=None
        stars = str(10000)
    print(stars,owners,language,license,date)
    if owners != None and owners !='':
        linkstr+='user%3A'+owners+'+'
    if date!=None and date != '':
        linkstr+='created%3A%3E'+date+'+'
    if stars!=None and stars!='':
        linkstr+='stars%3A%3E'+stars+'+'
    if license!=None and license!='':
        linkstr+='license%3A'+license+'+'
    if linkstr[-1]=='+':
        linkstr=linkstr[0:-1]
    print(linkstr)
    tmp1=mysearch.searchAdvanced(linkstr)
    print(len(tmp1))
    print('####')
    for ii in tmp1:
        ii.__repr__()
    return linkstr
if __name__ == '__main__':
    app.run()

Jinja2

  • 模板文件放在templates下 (html)
  • 静态文件放在static下 (css,png)
@app.route("/grand",methods = ['POST', 'GET'])
def grand():
    if request.method == 'POST':
        
    if request.method == 'GET':
 		
    plt.savefig('static\grandbar.png', stretch=100)
    cursor.execute(sql2)
    numnn = cursor.fetchall()
    print(numnn[0][0])
    return flask.render_template("grand.html" ,table=ans, numn=numnn[0][0])
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="{{ url_for('static', filename='index.css') }}">
</head>

<div class="card">
    <img src="{{ url_for('static', filename='grandbar.png') }}" width="1200" height="800" alt="直方图">
</div>
<table>
    <tr>
        <th class="w20">品牌图片</th>
        <th class="w20">品牌名</th>
        <th class="w20">销量</th>
        <th class="w20">国家</th>
        <th class="w20">相关图片</th>
        <th class="w20">销量详情</th>
    </tr>
    {% for row in table %}
    <tr>
        <td>
            <img src="https://i.img16888.com/carlogo75/{{ row[0] }}.gif" width="75" height="75" alt="品牌图片" title="品牌图片">
        </td>
        <td>
            {{ row[1] }}
        </td>
        <td>
            {{ row[2] }}
        </td>
        <td>
            {{ row[3] }}
        </td>
        <td>
            <a href="http://pic.16888.com/b/{{ row[0] }}/" target="_blank" id="link1">图片链接</a>
        </td>
        <td>
            <a href="https://xl.16888.com/b/{{ row[0] }}/" target="_blank" id="link1">详情链接</a>
        </td>
    </tr>
    {% endfor %}
</table>
<form action="/grand" method="post">
    <span class="filter">排序方式:</span>
    <select class="w1" name="p2">
        <option value="ASC">升序</option>
        <option selected value="DESC">降序</option>
    </select>
    <span class="filter">共有:{{ numn }}</span><span class="filter">条数据</span>
    <input type="text" name="p3" id="cid" value="" placeholder="页长" class="l20" /></td>
<input type="text" name="p4" id="cid" value="" placeholder="第几页" class="l20" /></td>
<input type="submit" class="sc1" value="查询">
<input type="reset" class="sc2" value="重置">
</form>
<body>
    <h1>登录</h1>
    {% if error %}
    <p><strong>Error:</strong> {{ error }}
        {% endif %}
    <form action = "/login" method ="POST">
        <dl>
            <dt>用户名:</dt>
            <dd>
                <input type = text name = "username" 
                       value = "{{request.form.username }}">
            </dd>
            <dt>密码:</dt>
            <dd><input type ="password" name ="password"></dd>
        </dl>
        <p><input type = submit value ="登录"></p>
    </form>
</body>
<body>
    {% with messages = get_flashed_messages() %}
    {% if messages %}
    <ul class=flashes>
        {% for message in messages %}
        <li>{{ message }}</li>
        {% endfor %}
    </ul>
    {% endif %}
    {% endwith %}
    <h1>Flask Message Flashing Example</h1>
    <p>您想要<a href = "{{ url_for('login') }}">
        <b>登录?</b></a></p>
</body>
from flask import Flask, flash, redirect, render_template, request, url_for
 app = Flask(__name__)
 app.secret_key = 'random string'
 @app.route('/')
 def index():
    return render_template('index.html')
 @app.route('/login', methods = ['GET', 'POST'])
 def login():
     error = None
     print(request.method)
     if request.method == 'POST':
         if request.form['username'] != 'admin' or \
             request.form['password'] != 'admin':
             error = 'Invalid username or password. Please try again!'
         else:
             #flash('您已成功登录')
             flash('You were successfully logged in')
             return redirect(url_for('index'))
     return render_template('login.html', error = error)
 if __name__ == "__main__":
     app.run(debug = True)
@app.route('/setcookie', methods = ['POST', 'GET'])
 def setcookie():
    if request.method == 'POST':
         user = request.form['name']
         resp = make_response(render_template('readcookie.html'))
         resp.set_cookie('userID', user)
         return resp
@app.route('/getcookie')
 def getcookie():
     name = request.cookies.get('userID')
     return '<h1>welcome '+name+'</h1>'    
from flask import Flask
 from flask import render_template
 from flask import request
 from flask import make_response
 from flask import Flask, session, redirect, url_for, escape, request
 app = Flask(__name__)
 app.secret_key = 'fkdjsafjdkfdlkjfadskjfadskljdsfklj'
 @app.route('/')
 def index():
     if 'username' in session:
         username = session['username']
         return '登录用户名是:' + username + '<br>' + \
                  "<b><a href = '/logout'>点击这里注销</a></b>"
     return "您暂未登录, <br><a href = '/login'></b>" + \
          "点击这里登录</b></a>"
 @app.route('/login', methods = ['GET', 'POST'])
 def login():
     if request.method == 'POST':
         session['username'] = request.form['username']
         return redirect(url_for('index'))
     return '''
    <form action = "" method = "post">
       <p><input type ="text" name ="username"/></p>
       <p><input type ="submit" value ="登录"/></p>
    </form>
    '''
 @app.route('/logout')
 def logout():
    # remove the username from the session if it is there
    session.pop('username', None)
    return redirect(url_for('index'))
 if __name__ == '__main__':
     app.run(debug = True)

重定向 错误

Flask.redirect(location, statuscode, response)
  • location 参数是响应应该被重定向的URL

  • statuscode 参数发送到浏览器的头标,默认为302

  • response 参数用于实例化响应

from flask import Flask, redirect, url_for, render_template, request
 # Initialize the Flask application
 app = Flask(__name__)
 @app.route('/')
 def index():
     return render_template('log_in.html')
 @app.route('/login',methods = ['POST', 'GET'])
 def login():
     if request.method == 'POST' and
         request.form['username'] == 'admin' :
         return redirect(url_for('success'))
     return redirect(url_for('index'))
 @app.route('/success')
 def success():
     return 'logged in successfully'
 if __name__ == '__main__':
     app.run(debug = True)
#带有错误代码的abort()函数
Flask.abort(code)

400 - 对于错误的请求401 - 用于未经身份验证403 - 禁止404 - 未找到406 - 不可接受415 - 用于不支持的媒体类型429 - 请求过多

from flask import Flask, redirect, url_for, render_template, request, abort
 app = Flask(__name__)
 @app.route('/')
 def index():
    return render_template('log_in.html')
 @app.route('/login',methods = ['POST', 'GET'])
 def login():
     if request.method == 'POST':
         if request.form['username'] == 'admin' :
             return redirect(url_for('success'))
         else:
             abort(401)
     else:
         return redirect(url_for('index'))
 @app.route('/success')
 def success():
     return 'logged in successfully'
 if __name__ == '__main__':
     app.run(debug = True)

文件上传

在Flask中处理文件上传非常简单。 它需要一个enctype属性设置为’multipart/form-data’的HTML表单,将该文提交到指定URL。 URL处理程序从request.files[]对象中提取文件并将其保存到所需的位置。

可以在Flask对象的配置设置中定义默认上传文件夹的路径和上传文件的最大大小。

变量 说明
app.config[‘UPLOAD_FOLDER’] 定义上传文件夹的路径
app.config[‘MAX_CONTENT_PATH’] 指定要上传的文件的最大大小 - 以字节为单位
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flask示例</title>
 </head>
    <body>
      <form action = "http://localhost:5000/upload" method = "POST" 
          enctype = "multipart/form-data">
          <input type = "file" name = "file" />
          <input type = "submit" value="提交"/>
       </form>
    </body>
 </html>
from flask import Flask, render_template, request
 from werkzeug import secure_filename
 app = Flask(__name__)
 @app.route('/upload', methods=['GET', 'POST'])
 def upload_file():
     if request.method == 'POST':
         f = request.files['file']
         print(request.files)
         f.save(secure_filename(f.filename))
         return 'file uploaded successfully'
     else:
         return render_template('upload.html')
 if __name__ == '__main__':
     app.run(debug = True)

其他

cainiaojc

部署

部署产品

uWSGI