章将介绍以下主题:
- 使用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}}℃</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>
可爱的python测试开发库 请在github上点赞,谢谢!
python中文库文档汇总
[雪峰磁针石博客]python3标准库-中文版
[雪峰磁针石博客]python3快速入门教程
接口自动化性能测试线上培训大纲
python测试开发自动化测试数据分析人工智能自学每周一练
更多内容请关注 雪峰磁针石:简书
-
技术支持qq群: 144081101(后期会录制视频存在该群群文件) 591302926 567351477 钉钉免费群:21745728
-
道家技术-手相手诊看相中医等钉钉群21734177 qq群:391441566 184175668 338228106 看手相、面相、舌相、抽签、体质识别。服务费50元每人次起。请联系钉钉或者微信pythontesting
网友评论