【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/

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是将 Flask 应用程序部署到 Windows 系统的步骤: 1. 安装 Python:在 Windows 上部署 Flask 应用程序之前,需要先安装 Python。您可以从官方网站下载并安装最新版本的 Python。 2. 安装虚拟环境:虚拟环境允许您在单个系统上运行多个 Python 应用程序,而不会互相干扰。在命令提示符中输入以下命令以安装虚拟环境: ``` pip install virtualenv ``` 3. 创建虚拟环境:在命令提示符中,导航到您的项目目录并创建一个新的虚拟环境。例如: ``` cd C:\project virtualenv venv ``` 4. 激活虚拟环境:在命令提示符中输入以下命令以激活虚拟环境: ``` venv\Scripts\activate ``` 5. 安装 Flask:在虚拟环境中,使用以下命令来安装 Flask: ``` pip install flask ``` 6. 编写 Flask 应用程序:在您的项目目录中创建一个名为 app.py 的 Python 文件,并在其中编写 Flask 应用程序的代码。 7. 运行 Flask 应用程序:在命令提示符中输入以下命令以启动 Flask 应用程序: ``` set FLASK_APP=app.py flask run ``` 这将启动一个本地服务器并运行 Flask 应用程序。在浏览器中访问 http://localhost:5000/,您应该能够看到您的应用程序在运行。 8. 配置生产环境:如果您要在生产环境中部署 Flask 应用程序,则需要使用一个 Web 服务器,如 Apache 或 Nginx。您可以使用 WSGI(Web 服务器网关接口)协议将 Flask 应用程序与 Web 服务器集成。例如,您可以使用 mod_wsgi 模块将 Flask 应用程序与 Apache 集成。 以上是将 Flask 应用程序部署到 Windows 系统的基本步骤。希望能对您有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值