Flask web 实践代码积累

1、表单参数传递最简代码

signin.html 里面表单的代码

<form class="form-signin" action="/gotomylink" method="post">
  <img class="mb-4" src="static/css/brand/bootstrap-solid.svg" alt="" width="72" height="72">
  <h1 class="h3 mb-3 font-weight-normal">请您登录</h1>
  <label for="inputEmail" class="sr-only">邮箱地址</label>
  <input type="email" id="inputEmail" name="email" class="form-control" placeholder="Email 地址" required autofocus>
  <label for="inputPassword" class="sr-only">密码</label>
  <input type="password" id="inputPassword" name="password" class="form-control" placeholder="输入密码" required>
  <div class="checkbox mb-3">
    <label>
      <input type="checkbox" value="remember-me"> 记住我
    </label>
  </div>
  <button class="btn btn-lg btn-primary btn-block" type="submit">登录</button>
  <p class="mt-5 mb-3 text-muted">&copy; 2017-2023</p>
</form>

解读:表单中文本框里面的组件貌似要有个name参数,才能把参数传递过去,在app.py中是是使用name来接参数的。
表单中 action=“/gotomylink” method=“post” 分别定义了响应地址和响应方式

app.py中接收form表单提交的参数的代码

@app.route('/gotomylink', methods=["POST"])
def gotomylink():
   email = request.form['email']
   password = request.form['password']
   return 'POST请求的参数是:{},{}'.format(email,password)

2、开发API,使用postman推送参数,编写代码接收数据。

用postman模拟推送以下数据

import requests
import json

body = {
      "name": "yanshu",
      "description": "yanshu's blog",
      "price": 100,
      "tax": 0
    }

body = json.dumps(body) # 需要先解析

response = requests.put('http://127.0.0.1:8000/items/3',data = body)
print(response.text)

接收端代码

from fastapi import FastAPI
from pydantic import BaseModel

# 将数据模型定义为继承BaseModel的类
class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None


app = FastAPI()

@app.put("/items/{item_id}")
async def create_item(item_id: int, item: Item, q: str = None):
    result = {"item_id": item_id, **item.dict()}
    if q:
        result.update({"q": q})
    return result

返回值 {“item_id”:3,“name”:“yanshu”,“description”:“yanshu’s blog”,“price”:100.0,“tax”:0.0}
原始教程位置: https://zhuanlan.zhihu.com/p/344366003

改良后的推送代码,实现压力测试循环推送数据。

import requests
import json


def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('PyCharm')

# See PyCharm help at https://www.jetbrains.com/help/pycharm/

body = {
      "name": "这里是循环鼹鼠",
      "description": "yanshu's blog",
      "price": 100,
      "tax": 0
    }

# body = json.dumps(body) # 经过实测,这里要注释掉才能跑的通
index = 1000
for i in range(index):
     response = requests.post('http://xxx.136.37.xxx/gotomylink',data = body)
     print(i+1)
     print(response.text)
     #经实测跑了3000条服务器就不响应了,1K以内随便跑没问题。

3、Jinjia2模板参数传递。

参数推送代码
原理:从ip地址接口获取数据,转换为json格式,以json格式存放到context大组里面,调用方式请参看模板代码。
这个接口是现炒现卖,从

@app.route('/contact')
def contact():
    url = 'http://ip-api.com/json/218.192.3.42'  # 英文免费
    #response1 = requests.get(url)
    # response2 = response1.json()

    context = {
        'username':'zhiliao',
        'age': 18,
        'country': 'china',
        'ipc': requests.get(url).json(),
        'signature': None'signature1':"世界很美好,你想不想去看看",
        'childrens': {
            'name':'安卓拉baby',
            'height': 180
        }

    }
    print(context)  #在控制台打印出要传递的所有参数,查看格式。
    return render_template('index.html',**context)

控制台打印结果:

{'username': 'zhiliao', 'age': 18, 'country': 'china', 'ipc': {'status': 'success', 'country': 'China', 'countryCode': 'CN', 'region': 'GD', 'regionName': 'Guangdong', 'city': 'Guangzhou', 'zip': '', 'lat': 23.1291, 'lon': 113.264, 'timezone': 'Asia/Shanghai', 'isp': 'CERNET', 'org': '', 'as': 'AS24357 CERNET2 IX at South China University of Technology', 'query': '218.192.3.42'}, 'childrens': {'name': '安卓拉baby', 'height': 180}}

参数接收模板代码(代码放在body里面即可)

<div  class="container">
    <h3>这是从模版中渲染的数据</h3>
    <p>用户名:{{ username }}</p>                                #调用变量参数
    <p>年龄:{{ age }}</p>
    <p>国家:{{ country }}</p>
    <p>名字:{{ childrens.name }}</p>                        #调用字典参数
    <p>名字:{{ childrens['name'] }}</p>
    <p>身高:{{ childrens.height }}cm</p>
    <br>
    <p>数据调用状态:{{ ipc.status }}</p>                     #调用JSON参数
    <p>国家:{{ ipc.country }}</p>
    <p>国家代码:{{ ipc.countryCode }}</p>
    <p>地区:{{ ipc.region }}</p>
    <p>地区名称:{{ ipc.regionName }}</p>
    <p>城市:{{ ipc.city }}</p>
    <p>单位名称:{{ ipc.as }}</p>
    <p>IP地址:{{ ipc.query }}</p>
    <p>个性签名:{{ signature | default("这是个大懒虫,没有留下签名",boolean = True) }}</p>   #default过滤器的用法
</div>

前端输出结果的body部分

<body>
<a class="mt-5 mb-3 text-muted" href="/login">访问登录页面</a>
<br>
<div  class="container">
    <h3>这是从模版中渲染的数据</h3>
    <p>用户名:zhiliao</p>
    <p>年龄:18</p>
    <p>国家:china</p>
    <p>名字:安卓拉baby</p>
    <p>名字:安卓拉baby</p>
    <p>身高:180cm</p>
    <br>
    <p>数据调用状态:success</p>
    <p>国家:China</p>
    <p>国家代码:CN</p>
    <p>地区:GD</p>
    <p>地区名称:Guangdong</p>
    <p>城市:Guangzhou</p>
    <p>单位名称:AS24357 CERNET2 IX at South China University of Technology</p>
    <p>IP地址:218.192.3.42</p>
    <p>个性签名:世界很美好,你想不想去看看</p>
</div>
</body>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值