[雪峰磁针石博客]flask构建自动化测试平台5-提高用户体验

简介:

5-提高用户体验

本章将介绍以下主题:

  • cookies
  • CSS

本文最新版本

代码: headlines.py

import feedparser
from flask import Flask
from flask import render_template
from flask import request
from flask import make_response

import datetime
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'
            }


def get_value_with_fallback(key):
    if request.args.get(key):
        return request.args.get(key)
    if request.cookies.get(key):
        return request.cookies.get(key)
    return DEFAULTS[key]


@app.route("/")
def home():
    # get customised headlines, based on user input or default
    publication = get_value_with_fallback("publication")
    articles = get_news(publication)

    # get customised weather based on user input or default
    city = get_value_with_fallback("city")
    weather = get_weather(city)

    # get customised currency based on user input or default
    currency_from = get_value_with_fallback("currency_from")
    currency_to = get_value_with_fallback("currency_to")
    rate, currencies = get_rate(currency_from, currency_to)

    # save cookies and return template
    response = make_response(render_template("home.html", articles=articles,
                                             weather=weather, currency_from=currency_from,
                                             currency_to=currency_to, rate=rate, currencies=sorted(currencies)))
    expires = datetime.datetime.now() + datetime.timedelta(days=365)
    response.set_cookie("publication", publication, expires=expires)
    response.set_cookie("city", city, expires=expires)
    response.set_cookie("currency_from", currency_from, expires=expires)
    response.set_cookie("currency_to", currency_to, expires=expires)
    return response


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.lower()])
    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>
    <style>
      html {
        font-family: "Helvetica";
        background: white;
      }

      body {
        background: lightgrey;
        max-width: 900px;
        margin: 0 auto;
      }

      #header {
        padding-top: 5;
        background: lightsteelblue;
      }

      #inner-header {
        padding-left: 10;
      }

      #main{
        padding-left: 10
      }

      input[type="text"], select {
        color: grey;
        border: 1px solid lightsteelblue;
        height: 30px;
        line-height:15px;
        margin: 2px 6px 16px 0px;
      }

      input[type="submit"] {
        padding: 5px 10px 5px 10px;
        color: black;
        background: lightsteelblue;
        border: none;
        box-shadow: 1px 1px 1px #4C6E91;
      }

      input[type="submit"]:hover{
        background: steelblue;
      }

      </style>   
    </head>
    <body>
      <div id="header">
        <div id="inner-header">
          <h1>Headlines</h1>
          <p>Headlines. Currency. Weather.</p>
        </div>
        <hr />
      </div>
      <div id="main">
        <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="publication" 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 %}

    </div>
  </body>
</html>

python_flask_autotest5.PNG

参考资料

相关文章
|
1月前
|
存储 运维 安全
构建高效自动化运维体系:Ansible与Docker的完美结合
【2月更文挑战第31天】 随着云计算和微服务架构的兴起,自动化运维成为保障系统稳定性和提升部署效率的关键手段。本文将详细探讨如何通过Ansible和Docker的结合来构建一个高效、可靠且易于管理的自动化运维体系。首先,介绍自动化运维的必要性及其在现代IT基础设施中的作用;然后,分别阐述Ansible和Docker的技术特点及优势;最后,提供一个基于Ansible和Docker结合使用的实践案例,以及实施过程中遇到的挑战和解决方案。
|
1月前
|
运维 Prometheus 监控
构建高效自动化运维系统的关键策略
【2月更文挑战第30天】随着云计算和微服务架构的兴起,现代IT运维环境变得愈加复杂多变。为保持业务连续性、提高响应速度并降低成本,企业亟需构建一个高效的自动化运维系统。本文将深入探讨自动化运维系统构建过程中的关键策略,包括工具和技术选型、流程优化、监控与告警体系搭建以及持续集成/持续部署(CI/CD)实践,旨在为读者提供一个清晰的构建蓝图和实用的实施建议。
|
1月前
|
运维 Kubernetes 监控
构建高效自动化运维体系:基于Docker和Kubernetes的实践指南
【2月更文挑战第30天】 在当今快速发展的云计算时代,传统的IT运维模式已难以满足业务的敏捷性和稳定性需求。本文深入探讨了如何通过Docker容器化技术和Kubernetes集群管理工具构建一个高效、可靠的自动化运维体系。文章首先概述了容器化技术和微服务架构的基本概念,随后详细阐述了基于Docker的应用打包、部署流程,以及Kubernetes在自动化部署、扩展和管理容器化应用中的关键作用。最后,文中通过案例分析,展示了如何在实际场景中利用这些技术优化运维流程,提高系统的整体效率和可靠性。
|
1月前
|
运维 安全 网络安全
构建高效自动化运维体系:Ansible与Docker的完美融合
【2月更文挑战第30天】在当今快速迭代和持续部署的软件发展环境中,自动化运维成为确保效率和稳定性的关键。本文将探讨如何通过结合Ansible和Docker技术,构建一个高效的自动化运维体系。我们将分析Ansible的配置管理功能和Docker容器化的优势,并展示它们如何协同工作以简化部署流程,增强应用的可移植性,并提供一致性的系统环境。此外,文章还将介绍一些最佳实践,帮助读者在真实环境中实现这一整合方案。
|
29天前
|
运维 监控 安全
构建高效自动化运维体系的五大关键步骤
在当今快速发展的IT环境中,自动化已经成为提高运维效率、减少人为错误和响应快速变化的关键。本文将深入探讨构建一个高效自动化运维体系的核心步骤,包括工具选择、流程设计、系统集成、安全策略以及持续改进。通过这些步骤,企业可以确保其运维团队能够更加高效地管理日常任务,同时保持系统的稳定性和安全性。
|
30天前
|
运维 监控 持续交付
构建高效自动化运维体系:策略与实践
在数字化时代,企业IT基础设施的管理和维护变得日益复杂。为了提高效率、降低错误率并快速响应市场变化,构建一个高效的自动化运维体系至关重要。本文将探讨自动化运维的核心策略,并通过实际案例分析展示如何将这些策略应用于日常管理中,以实现IT运维的优化。
17 0
|
1月前
|
人工智能 运维 监控
构建高性能微服务架构:现代后端开发的挑战与策略构建高效自动化运维系统的关键策略
【2月更文挑战第30天】 随着企业应用的复杂性增加,传统的单体应用架构已经难以满足快速迭代和高可用性的需求。微服务架构作为解决方案,以其服务的细粒度、独立性和弹性而受到青睐。本文将深入探讨如何构建一个高性能的微服务系统,包括关键的设计原则、常用的技术栈选择以及性能优化的最佳实践。我们将分析微服务在处理分布式事务、数据一致性以及服务发现等方面的挑战,并提出相应的解决策略。通过实例分析和案例研究,我们的目标是为后端开发人员提供一套实用的指南,帮助他们构建出既能快速响应市场变化,又能保持高效率和稳定性的微服务系统。 【2月更文挑战第30天】随着信息技术的飞速发展,企业对于信息系统的稳定性和效率要求
|
8天前
|
运维 Kubernetes Devops
构建高效自动化运维体系:DevOps与容器技术融合实践
【4月更文挑战第15天】 在当今快速发展的信息技术时代,传统的IT运维模式已难以满足业务敏捷性的需求。本文旨在探讨如何通过整合DevOps理念和容器技术来构建一个高效的自动化运维体系。文章将详细阐述DevOps的核心原则、容器技术的基础知识,以及两者结合的优势。此外,文中还将分享一系列实践经验,包括持续集成/持续部署(CI/CD)流程的搭建、微服务架构的应用,以及监控和日志管理策略的优化,以期帮助企业实现快速、可靠且安全的软件交付过程。
|
10天前
|
人工智能 运维 监控
构建高效自动化运维体系的实践与思考
【4月更文挑战第14天】在数字化转型的浪潮中,自动化运维作为提升系统稳定性和效率的关键手段,受到了企业的广泛关注。本文将深入探讨如何构建一个高效的自动化运维体系,涵盖从基础设施的搭建到流程的优化等多个方面。通过分析当前自动化运维的挑战及解决方案,文章旨在为读者提供一套实用的策略框架,帮助企业实现运维工作的高效化、标准化和智能化。
|
14天前
|
机器学习/深度学习 存储 运维
构建高效自动化运维体系的五大策略
【4月更文挑战第10天】在数字化转型的浪潮中,企业IT基础设施的复杂性与日俱增,传统的手动运维模式已难以满足快速响应和高效率的需求。本文将探讨构建一个高效自动化运维体系的五大策略,包括监控与告警的智能化、配置管理自动化、故障自愈能力的提升、日志管理的优化以及持续集成和部署(CI/CD)的实践。这些策略将帮助企业减轻运维负担,提高系统稳定性和业务敏捷性。