[雪峰磁针石博客]flask构建自动化测试平台4-用户输入

简介:

本章将介绍以下主题:

  • 使用HTTP GET获取用户输入
  • 使用HTTP POST获取用户输入
  • 添加天气和货币数据

GET

HTTP GET从用户获取有限的非敏感信息,以便服务器根据GET参数的要求返回页面。GET请求不应该修改服务器状态,用户应该多次请求返回相同的结果。

全局变量request已经帮你处理好了请求顺序和线程。参考资料

POST

HTTP POST用于提交更大的数据块或更敏感的数据到服务器。 通过POST请求发送的数据在网址中不可见。

实例

代码: headlines.py

import feedparser
from flask import Flask
from flask import render_template
from flask import request
import json
import urllib

app = Flask(__name__)

RSS_FEEDS = {'bbc': 'http://feeds.bbci.co.uk/news/rss.xml',
             'cnn': 'http://rss.cnn.com/rss/edition.rss',
             'fox': 'http://feeds.foxnews.com/foxnews/latest',
             'iol': 'http://www.iol.co.za/cmlink/1.640'}

WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&APPID=cb932829eacb6a0e9ee4f38bfbf112ed"
CURRENCY_URL = "https://openexchangerates.org//api/latest.json?app_id=b23c94daab584f4580e4e2bf75cbcf7e"

DEFAULTS = {'publication': 'bbc',
            'city': 'London,UK',
            'currency_from': 'GBP',
            'currency_to': 'USD'
            }


@app.route("/")
def home():
    # get customised headlines, based on user input or default
    publication = request.args.get('publication')
    if not publication:
        publication = DEFAULTS['publication']
    articles = get_news(publication)
    # get customised weather based on user input or default
    city = request.args.get('city')
    if not city:
        city = DEFAULTS['city']
    weather = get_weather(city)
    # get customised currency based on user input or default
    currency_from = request.args.get("currency_from")
    if not currency_from:
        currency_from = DEFAULTS['currency_from']
    currency_to = request.args.get("currency_to")
    if not currency_to:
        currency_to = DEFAULTS['currency_to']
    rate, currencies = get_rate(currency_from, currency_to)
    return render_template("home.html", articles=articles, weather=weather,
                           currency_from=currency_from, currency_to=currency_to, rate=rate,
                           currencies=sorted(currencies))


def get_rate(frm, to):
    all_currency = urllib.request.urlopen(CURRENCY_URL).read().decode('utf-8') 
    parsed = json.loads(all_currency).get('rates')
    frm_rate = parsed.get(frm.upper())
    to_rate = parsed.get(to.upper())
    return (to_rate / frm_rate, parsed.keys())


def get_news(publication):
    feed = feedparser.parse(RSS_FEEDS[publication])
    return feed['entries']


def get_weather(query):
    query = urllib.parse.quote(query)
    url = WEATHER_URL.format(query)
    data = urllib.request.urlopen(url).read().decode('utf-8')
    parsed = json.loads(data)
    weather = None
    if parsed.get('weather'):
        weather = {'description': parsed['weather'][0]['description'],
                   'temperature': parsed['main']['temp'],
                   'city': parsed['name'],
                   'country': parsed['sys']['country']
                   }
    return weather

if __name__ == "__main__":
    app.run(host='0.0.0.0',port=8000, debug=True)

home.html



<html>
    <head>
        <title>Headlines</title>
    </head>
    <body>
        <h1>Headlines</h1>

        <h2>Current weather</h2>

        <form>
          <input type="text" name="city" placeholder="weather search">
          <input type="submit" value="Submit">
        </form>

        <p>City: <b>{{weather.city}}, {{weather.country}}</b></p>
        <p>{{weather.description}} |{{weather.temperature}}&#8451</p>

        <h2>Currency</h2>

        <form>
            from: <select name="currency_from">
                    {% for currency in currencies %}
                        <option value="{{currency}}" {{'selected="selected"' if currency_from==currency}}>{{currency}}</option>
                    {% endfor %}
                  </select>

             to: <select name="currency_to">
                    {% for currency in currencies %}
                        <option value="{{currency}}" {{'selected="selected"' if currency_to==currency}}>{{currency}}</option>
                    {% endfor %}
                  </select>
                 <input type="submit" value="Submit">
        </form>

        1 {{currency_from}} = {{currency_to}} {{rate}}

        <h2>Headlines</h2>
        <form>
          <input type="text" name="query" placeholder="search" />
          <input type="submit" value="Submit" />
        </form>

        {% for article in articles %}
            <b><a href="{{article.link}}">{{article.title}}</a></b><br />
            <i>{{article.published}}</i><br />
            <p>{{article.summary}}</p> 
            <hr />
        {% endfor %}
     
    </body>
</html>

image.png

参考资料

相关文章
|
2月前
|
资源调度 测试技术 Linux
一款接口自动化神器—开源接口测试平台Lim(Less is More)
一款接口自动化神器—开源接口测试平台Lim(Less is More)
130 2
|
3天前
|
人工智能 监控 数据处理
【AI大模型应用开发】【LangSmith: 生产级AI应用维护平台】1. 快速上手数据集与测试评估过程
【AI大模型应用开发】【LangSmith: 生产级AI应用维护平台】1. 快速上手数据集与测试评估过程
18 0
|
11天前
|
数据库 开发者 Python
Python中使用Flask构建简单Web应用的例子
【4月更文挑战第15天】Flask是一个轻量级的Python Web框架,它允许开发者快速搭建Web应用,同时保持代码的简洁和清晰。下面,我们将通过一个简单的例子来展示如何在Python中使用Flask创建一个基本的Web应用。
|
1月前
|
缓存 运维 Serverless
应用研发平台EMAS产品常见问题之测试检查更新没有反应如何解决
应用研发平台EMAS(Enterprise Mobile Application Service)是阿里云提供的一个全栈移动应用开发平台,集成了应用开发、测试、部署、监控和运营服务;本合集旨在总结EMAS产品在应用开发和运维过程中的常见问题及解决方案,助力开发者和企业高效解决技术难题,加速移动应用的上线和稳定运行。
|
1月前
|
机器学习/深度学习 人工智能 监控
视觉智能平台常见问题之体验产品的美颜测试关掉如何解决
视觉智能平台是利用机器学习和图像处理技术,提供图像识别、视频分析等智能视觉服务的平台;本合集针对该平台在使用中遇到的常见问题进行了收集和解答,以帮助开发者和企业用户在整合和部署视觉智能解决方案时,能够更快地定位问题并找到有效的解决策略。
24 1
|
1月前
|
存储 数据可视化 API
Python项目开发:Flask基于Python的天气数据可视化平台
Python项目开发:Flask基于Python的天气数据可视化平台
50 0
|
1月前
|
存储 开发框架 人工智能
使用Python和Flask构建简单的博客后端
使用Python和Flask构建简单的博客后端
21 0
|
1月前
|
JSON 中间件 Shell
使用Python和Flask构建RESTful API
使用Python和Flask构建RESTful API
23 0
|
1月前
|
JSON API 数据格式
构建高效Python Web应用:Flask框架与RESTful API设计实践
【2月更文挑战第17天】在现代Web开发中,轻量级框架与RESTful API设计成为了提升应用性能和可维护性的关键。本文将深入探讨如何使用Python的Flask框架来构建高效的Web服务,并通过具体实例分析RESTful API的设计原则及其实现过程。我们将从基本的应用架构出发,逐步介绍如何利用Flask的灵活性进行模块化开发,并结合请求处理、数据验证以及安全性考虑,打造出一个既符合标准又易于扩展的Web应用。
653 4
|
2月前
|
测试技术
Lim测试平台测试报告说明
Lim测试平台测试报告说明
32 2