Bootstrap

【python】flask部署

1,flask介绍
    Flask是微框架,因为它仅仅实现了Web应用的核心功能:Flask由两个主要依赖组成(提供路由、调试和Web服务器网关接口的Werkzeug和提供模板的Jinja2)。其他的一切(比如数据库集成,表单处理,文件上传,用户认证)都由第三方库来完成,如果插件满足不了你的需求,你也可以自行开发。

2,具体案例
2.1 目录结构

.
├── photo        
├── index.html   
└── main.py      
.
├── index.html       # 静态页面
├── photo            # 上传图片保存文件
├── start_flask.py   # flask启动文件
└── templates        # flask静态页面文件,必须固定
    └── back.html    # 跳转到:back.html
    └── hello.html   # 跳转到:hello.html

2.2 start_flask.py

# -*- coding: utf-8 -*-
import os, json
from flask import Flask, request, render_template, redirect, jsonify, make_response
from datetime import datetime

app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__)) # 绝对路径与相对路径的转化

ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.before_request
def before_request():
    token = request.headers.get("token") # 获取token参数,用作校验
    is_valid, result = token_check.check_token(token) # 验证码校验
    if not is_valid:
        return make_response(result)

# 上传文件
@app.route('/up_photo', methods=['post'])
def up_photo():
    img = request.files.get('photo')
    username = request.form.get('name')
    if allowed_file(img.filename):
        path = basedir + '/photo/'
        file_path = path + datetime.now().strftime("%Y%m%d%H%M%S") + '.' + img.filename.rsplit('.', 1)[1]
        img.save(file_path)
        return "上传文件格式正确"
    return '上传文件格式错误'

# 页面跳转
@app.route('/submit')
def submit():
    return render_template("back.html")
    
# 页面跳转,传入参数
@app.route('/hello/')
@app.route('/hello/<string:name>')
def hello(name=None):
    return render_template('hello.html', name=name, age=13)

# API接口部署,调用方式:http://127.0.0.1:5000/get_answer/question=111
@app.route('/get_answer/<string:question>', methods=['GET'])
def get_answer(question):
    print(question)
    answer = "逍遥派掌门人无崖子"
    return jsonify({'answer': answer})
    
# API部署,传入两个参数,调用方式:http://127.0.0.1:5000/index?question=Class叫谁&type=1
@app.route('/index', methods=['post','get'])
def index():
    question = request.args.get('question')
    type = request.args.get('type')
    result = "question = {} and type = {}".format(question, type)
    return result
 
# 接收字典传来的参数,请求方式POST
@app.route("/get_dict", methods=["POST"])
def index():
    data_json = json.loads(request.get_data(as_text=True))
    print(data_json)
    return data_json

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

2.3 index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<body>
    <div>
        <form method="post" action="http://localhost:5000/up_photo" enctype="multipart/form-data">
        <input type="file" size="30" name="photo" />
        <br>
        <input type="text" class="txt_input" name="name" style="margin-top:15px;" />
        <input type="submit" value="提交信息" class="button-new" style="margin-top:15px;" />
        </form>
    </div>
</body>

</html>

2.4 back.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<body>
    <span>提交成功</span>
</body>

</html>

2.5,hello.html

<!DOCTYPE html>
<title>Hello from Flask</title>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello, World</h1>
{% endif %}

{% if age %}
<h1>Age is {{ age }}!</h1>
{% else %}
<h1>Age is null</h1>
{% endif %}

3,flask传入json字符串,接收数据

def http_post_json(url: str, params: str): # 将json变为string
    url_path = url
    r = requests.post(url=url_path, data=params.encode('utf-8'))
    r.headers['content-type'] = 'application/json; charset=utf-8'
    r.encoding = 'utf-8'
    return r.text

4,flask Blueprint 访问不同的页面
4.1 目录结构

rose@rose-machine:~/flask$ tree
├── web
│   ├── __init__.py
│   ├── login.py
└── app.py 

4.2 login.py

from flask import Blueprint

login= Blueprint('login', __name__)

@login.route('/index', methods=["GET"])
def index():
    return "login index"

4.3 app.py

from flask import Flask
from web.login import login

app = Flask(__name__)

app.register_blueprint(login, url_prefix='/login') # 注册接口

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

4.4 网页访问
http://127.0.0.1:5000/login/index

5,服务器启动进程

nohup python -u start.py > /dev/null 2>&1 # 启动后父进程为1

7,指令发送请求

curl -X POST "http://127.0.0.1:7304/func" -H "accept: */*" -H "Content-Type: application/json" -d "{\"api_flag\":True}"

数据:"{\"api_flag\":True}",类型,字符串

6,flask高并发
https://blog.csdn.net/zmy941110/article/details/89639883/

;