Chapter 14: Using Web Services | Python for Everybody 讲义笔记_En

文章目录

  • Python for Everybody
    • 课程简介
    • Python and Web Services
      • Using Web Services
      • eXtensible Markup Language - XML
      • Parsing XML
      • JavaScript Object Notation - JSON
      • Parsing JSON
      • Application Programming Interfaces
      • Security and API usage
      • Glossary


Python for Everybody

Exploring Data Using Python 3
Dr. Charles R. Severance


课程简介

Python for Everybody 零基础程序设计(Python 入门)

  • This course aims to teach everyone the basics of programming computers using Python. 本课程旨在向所有人传授使用 Python 进行计算机编程的基础知识。
  • We cover the basics of how one constructs a program from a series of simple instructions in Python. 我们介绍了如何通过 Python 中的一系列简单指令构建程序的基础知识。
  • The course has no pre-requisites and avoids all but the simplest mathematics. Anyone with moderate computer experience should be able to master the materials in this course. 该课程没有任何先决条件,除了最简单的数学之外,避免了所有内容。任何具有中等计算机经验的人都应该能够掌握本课程中的材料。
  • This course will cover Chapters 1-5 of the textbook “Python for Everybody”. Once a student completes this course, they will be ready to take more advanced programming courses. 本课程将涵盖《Python for Everyday》教科书的第 1-5 章。学生完成本课程后,他们将准备好学习更高级的编程课程。
  • This course covers Python 3.

在这里插入图片描述

coursera

Python for Everybody 零基础程序设计(Python 入门)

Charles Russell Severance
Clinical Professor

在这里插入图片描述

个人主页
Twitter

在这里插入图片描述

University of Michigan


课程资源

coursera原版课程视频
coursera原版视频-中英文精校字幕-B站
Dr. Chuck官方翻录版视频-机器翻译字幕-B站

PY4E-课程配套练习
Dr. Chuck Online - 系列课程开源官网



Python and Web Services

Web services allow a program to access data available in a different server.


Using Web Services

Once it became easy to retrieve documents and parse documents over HTTP using programs, it did not take long to develop an approach where we started producing documents that were specifically designed to be consumed by other programs (i.e., not HTML to be displayed in a browser).

There are two common formats that we use when exchanging data across the web. eXtensible Markup Language (XML) has been in use for a very long time and is best suited for exchanging document-style data. When programs just want to exchange dictionaries, lists, or other internal information with each other, they use JavaScript Object Notation (JSON) (see www.json.org). We will look at both formats.


eXtensible Markup Language - XML

XML looks very similar to HTML, but XML is more structured than HTML. Here is a sample of an XML document:

<person><name>Chuck</name><phone type="intl">+1 734 303 4456</phone><email hide="yes" />
</person>

Each pair of opening (e.g., <person>) and closing tags (e.g., </person>) represents a element or node with the same name as the tag (e.g., person). Each element can have some text, some attributes (e.g., hide), and other nested elements. If an XML element is empty (i.e., has no content), then it may be depicted by a self-closing tag (e.g., <email />).

Often it is helpful to think of an XML document as a tree structure where there is a top element (here: person), and other tags (e.g., phone) are drawn as children of their parent elements.


在这里插入图片描述
A Tree Representation of XML



Parsing XML

Here is a simple application that parses some XML and extracts some data elements from the XML:

import xml.etree.ElementTree as ETdata = '''
<person><name>Chuck</name><phone type="intl">+1 734 303 4456</phone><email hide="yes" />
</person>'''tree = ET.fromstring(data)
print('Name:', tree.find('name').text)
print('Attr:', tree.find('email').get('hide'))# Code: http://www.py4e.com/code3/xml1.py

The triple single quote ('''), as well as the triple double quote ("""), allow for the creation of strings that span multiple lines.

Calling fromstring converts the string representation of the XML into a “tree” of XML elements. When the XML is in a tree, we have a series of methods we can call to extract portions of data from the XML string. The find function searches through the XML tree and retrieves the element that matches the specified tag.

Name: Chuck
Attr: yes

Often the XML has multiple nodes and we need to write a loop to process all of the nodes. In the following program, we loop through all of the user nodes:

import xml.etree.ElementTree as ETinput = '''
<stuff><users><user x="2"><id>001</id><name>Chuck</name></user><user x="7"><id>009</id><name>Brent</name></user></users>
</stuff>'''stuff = ET.fromstring(input)
lst = stuff.findall('users/user')
print('User count:', len(lst))for item in lst:print('Name', item.find('name').text)print('Id', item.find('id').text)print('Attribute', item.get('x'))# Code: http://www.py4e.com/code3/xml2.py

The findall method retrieves a Python list of subtrees that represent the user structures in the XML tree. Then we can write a for loop that looks at each of the user nodes, and prints the name and id text elements as well as the x attribute from the user node.

User count: 2
Name Chuck
Id 001
Attribute 2
Name Brent
Id 009
Attribute 7

It is important to include all parent level elements in the findall statement except for the top level element (e.g., users/user). Otherwise, Python will not find any desired nodes.

import xml.etree.ElementTree as ETinput = '''
<stuff><users><user x="2"><id>001</id><name>Chuck</name></user><user x="7"><id>009</id><name>Brent</name></user></users>
</stuff>'''stuff = ET.fromstring(input)lst = stuff.findall('users/user')
print('User count:', len(lst))lst2 = stuff.findall('user')
print('User count:', len(lst2))

lst stores all user elements that are nested within their users parent. lst2 looks for user elements that are not nested within the top level stuff element where there are none.

User count: 2
User count: 0

JavaScript Object Notation - JSON

The JSON format was inspired by the object and array format used in the JavaScript language. But since Python was invented before JavaScript, Python’s syntax for dictionaries and lists influenced the syntax of JSON. So the format of JSON is nearly identical to a combination of Python lists and dictionaries.

Here is a JSON encoding that is roughly equivalent to the simple XML from above:

{"name" : "Chuck","phone" : {"type" : "intl","number" : "+1 734 303 4456"},"email" : {"hide" : "yes"}
}

You will notice some differences. First, in XML, we can add attributes like “intl” to the “phone” tag. In JSON, we simply have key-value pairs. Also the XML “person” tag is gone, replaced by a set of outer curly braces.

In general, JSON structures are simpler than XML because JSON has fewer capabilities than XML. But JSON has the advantage that it maps directly to some combination of dictionaries and lists. And since nearly all programming languages have something equivalent to Python’s dictionaries and lists, JSON is a very natural format to have two cooperating programs exchange data.

JSON is quickly becoming the format of choice for nearly all data exchange between applications because of its relative simplicity compared to XML.


Parsing JSON

We construct our JSON by nesting dictionaries and lists as needed. In this example, we represent a list of users where each user is a set of key-value pairs (i.e., a dictionary). So we have a list of dictionaries.

In the following program, we use the built-in json library to parse the JSON and read through the data. Compare this closely to the equivalent XML data and code above. The JSON has less detail, so we must know in advance that we are getting a list and that the list is of users and each user is a set of key-value pairs. The JSON is more succinct (an advantage) but also is less self-describing (a disadvantage).

import jsondata = '''
[{ "id" : "001","x" : "2","name" : "Chuck"} ,{ "id" : "009","x" : "7","name" : "Brent"}
]'''info = json.loads(data)
print('User count:', len(info))for item in info:print('Name', item['name'])print('Id', item['id'])print('Attribute', item['x'])# Code: http://www.py4e.com/code3/json2.py

If you compare the code to extract data from the parsed JSON and XML you will see that what we get from json.loads() is a Python list which we traverse with a for loop, and each item within that list is a Python dictionary. Once the JSON has been parsed, we can use the Python index operator to extract the various bits of data for each user. We don’t have to use the JSON library to dig through the parsed JSON, since the returned data is simply native Python structures.

The output of this program is exactly the same as the XML version above.

User count: 2
Name Chuck
Id 001
Attribute 2
Name Brent
Id 009
Attribute 7

In general, there is an industry trend away from XML and towards JSON for web services. Because the JSON is simpler and more directly maps to native data structures we already have in programming languages, the parsing and data extraction code is usually simpler and more direct when using JSON. But XML is more self-descriptive than JSON and so there are some applications where XML retains an advantage. For example, most word processors store documents internally using XML rather than JSON.


Application Programming Interfaces

We now have the ability to exchange data between applications using HyperText Transport Protocol (HTTP) and a way to represent complex data that we are sending back and forth between these applications using eXtensible Markup Language (XML) or JavaScript Object Notation (JSON).

The next step is to begin to define and document “contracts” between applications using these techniques. The general name for these application-to-application contracts is Application Program Interfaces (APIs). When we use an API, generally one program makes a set of services available for use by other applications and publishes the APIs (i.e., the “rules”) that must be followed to access the services provided by the program.

When we begin to build our programs where the functionality of our program includes access to services provided by other programs, we call the approach a Service-oriented architecture (SOA). A SOA approach is one where our overall application makes use of the services of other applications. A non-SOA approach is where the application is a single standalone application which contains all of the code necessary to implement the application.

We see many examples of SOA when we use the web. We can go to a single web site and book air travel, hotels, and automobiles all from a single site. The data for hotels is not stored on the airline computers. Instead, the airline computers contact the services on the hotel computers and retrieve the hotel data and present it to the user. When the user agrees to make a hotel reservation using the airline site, the airline site uses another web service on the hotel systems to actually make the reservation. And when it comes time to charge your credit card for the whole transaction, still other computers become involved in the process.


在这里插入图片描述
Service-oriented architecture


A Service-oriented architecture has many advantages, including: (1) we always maintain only one copy of data (this is particularly important for things like hotel reservations where we do not want to over-commit) and (2) the owners of the data can set the rules about the use of their data. With these advantages, an SOA system must be carefully designed to have good performance and meet the user’s needs.

When an application makes a set of services in its API available over the web, we call these web services.


Security and API usage

It is quite common that you need an API key to make use of a vendor’s API. The general idea is that they want to know who is using their services and how much each user is using. Perhaps they have free and pay tiers of their services or have a policy that limits the number of requests that a single individual can make during a particular time period.

Sometimes once you get your API key, you simply include the key as part of POST data or perhaps as a parameter on the URL when calling the API.

Other times, the vendor wants increased assurance of the source of the requests and so they expect you to send cryptographically signed messages using shared keys and secrets. A very common technology that is used to sign requests over the Internet is called OAuth. You can read more about the OAuth protocol at www.oauth.net.

Thankfully there are a number of convenient and free OAuth libraries so you can avoid writing an OAuth implementation from scratch by reading the specification. These libraries are of varying complexity and have varying degrees of richness. The OAuth web site has information about various OAuth libraries.


Glossary

API
Application Program Interface - A contract between applications that defines the patterns of interaction between two application components.
ElementTree
A built-in Python library used to parse XML data.
JSON
JavaScript Object Notation - A format that allows for the markup of structured data based on the syntax of JavaScript Objects.
SOA
Service-Oriented Architecture - When an application is made of components connected across a network.
XML
eXtensible Markup Language - A format that allows for the markup of structured data.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/101061.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

java 项目运行时,后端控制台出现空指针异常---java.lang.NullPointerException

项目场景&#xff1a; 提示&#xff1a;这里简述项目背景&#xff1a; 场景如下&#xff1a; java 项目运行时&#xff0c;后端控制台出现如下图所示报错信息&#xff1a;— 问题描述 提示&#xff1a;这里描述项目中遇到的问题&#xff1a; java 项目运行时&#xff0c;后…

代码随想录算法训练营第60天|动态规划part17| 647. 回文子串、516.最长回文子序列、动态规划总结篇

代码随想录算法训练营第60天&#xff5c;动态规划part17&#xff5c; 647. 回文子串、516.最长回文子序列、动态规划总结篇 647. 回文子串 647. 回文子串 思路&#xff1a; 暴力解法 两层for循环&#xff0c;遍历区间起始位置和终止位置&#xff0c;然后还需要一层遍历判断…

Redis原理剖析

一、Redis简介 Redis是一个开源的&#xff0c;基于网络的&#xff0c;高性能的key-value数据库&#xff0c;弥补了memcached这类key-value存储的不足&#xff0c;在部分场合可以对关系数据库起到很好的补充作用&#xff0c;满足实时的高并发需求。 Redis跟memcached类似&#…

SqlServer 快速数据库脚本迁移

文章目录 前言数据库脚本数据库->任务->生成脚本选择数据库对象高级 如何迁移&#xff1a;脚本修改 如何使用新建数据库 前言 做工业的&#xff0c;经常遇到内网的项目&#xff0c;就是数据往本地的数据库传。由于这个问题所以我们需要新建一个数据库。最合适的就是数据…

App Tamer for Mac CPU智能控制管理

App Tamer是一款针对 macOS 平台的软件&#xff0c;它可以帮助用户有效地管理和控制正在运行的应用程序。通过优化 CPU 使用率&#xff0c;减少电池消耗和降低系统负载&#xff0c;App Tamer 提供了更加流畅和高效的计算体验。 App Tamer 的主要特点包括&#xff1a; 智能控制&…

使用R语言绘制折线图

写在前面 昨天我们分享了使用Python绘制折线图的教程,跟着NC学作图 | 使用python绘制折线图,考虑到很多同学基本不使用Python绘图。那么,我们也使用R语言复现此图形。 此外,在前期的教程中,我们基本没有分享过折线图的教程。因此,我们在这里也制作一期关于折线图的教程。…

财务数据分析模板有哪些,能满足决策吗?

虽然企业的业务经营各有不同&#xff0c;但在财务数据分析上却有着相似的需求与流程&#xff0c;因此财务数据分析是可以形成一套标准化模板的。奥威BI数据可视化工具从多年丰富的BI项目中总结经验&#xff0c;形成一套标准化、系统化的财务数据分析模板&#xff0c;内含资产负…

基本定时器

1.简介 1. 基本定时器 TIM6 和 TIM7 包含一个 16 位自动重载计数器 2. 可以专门用于驱动数模转换器 (DAC), 用于触发 DAC 的同步电路 3. 16 位自动重载递增计数器 4. 16 位可编程预分频器 5. 计数器溢出时, 会触发中断/DMA请求 从上往下看 1.开始RCC供给定时器的时钟 RCC_APB1…

.NET6.0 System.Drawing.Common 通用解决办法

最近有不少小伙伴在升级 .NET 6 时遇到了 System.Drawing.Common 的问题&#xff0c;同时很多库的依赖还都是 System.Drawing.Common &#xff0c;而 .NET 6 默认情况下只在 Windows 上支持使用&#xff0c;Linux 上默认不支持这就导致在 Linux 环境上使用会有问题&#xff0c;…

python35种绘图函数总结,3D、统计、流场,实用性拉满

文章目录 基础图误差线三维图等高线图场图统计图非结构坐标图 基础图 下面这8种图像一般只有两组坐标&#xff0c;直观容易理解。 函数坐标参数图形类别plotx,y曲线图stackplotx,y散点图stemx,y茎叶图scatterx,y散点图polarx,y极坐标图stepx,y步阶图barx,y条形图barhx,y横向条…

Electron 报gpu_process_host.cc(951)] GPU process launch faile错误

解决方法&#xff0c;在入口js文件中&#xff0c;添加如下代码: app.commandLine.appendSwitch(no-sandbox)

8.3.tensorRT高级(3)封装系列-tensor封装,索引计算,内存标记及自动复制

目录 前言1. Tensor封装总结 前言 杜老师推出的 tensorRT从零起步高性能部署 课程&#xff0c;之前有看过一遍&#xff0c;但是没有做笔记&#xff0c;很多东西也忘了。这次重新撸一遍&#xff0c;顺便记记笔记。 本次课程学习 tensorRT 高级-tensor封装&#xff0c;索引计算&a…

定向流量卡怎么没人买了呢?你知道定向流量卡有多坑吗?

在购买流量卡的时候大家可能都注意了&#xff0c;市面上的流量卡有三种&#xff0c;定向流量卡&#xff0c;通用流量卡&#xff0c;通用流量定向流量卡&#xff0c;据小编了解&#xff0c;现在越来越多的人比较喜欢购买后两者&#xff0c;而关注定向流量卡越来越少了。 其实用过…

7.11 Java方法重写

7.11 Java方法重写 这里首先要确定的是重写跟属性没有关系&#xff0c;重写都是方法的重写&#xff0c;与属性无关 带有关键字Static修饰的方法的重写实例 父类实例 package com.baidu.www.oop.demo05;public class B {public static void test(){System.out.println("这…

clickhouse(十四、分布式DDL阻塞及同步阻塞问题)

文章目录 一、分布式ddl 阻塞、超时现象验证方法解决方案 二、副本同步阻塞现象验证解决方案 一、分布式ddl 阻塞、超时 现象 在clickhouse 集群的操作中&#xff0c;如果同时执行一些重量级变更语句&#xff0c;往往会引起阻塞。 一般是由于节点堆积过多耗时的ddl。然后抛出…

机器学习笔记之优化算法(十五)Baillon Haddad Theorem简单认识

机器学习笔记之优化算法——Baillon Haddad Theorem简单认识 引言 Baillon Haddad Theorem \text{Baillon Haddad Theorem} Baillon Haddad Theorem简单认识证明过程证明&#xff1a;条件 1 ⇒ 1 \Rightarrow 1⇒ 条件 2 2 2证明&#xff1a;条件 3 ⇒ 3 \Rightarrow 3⇒条件 1…

YOLO目标检测——动漫头像数据集下载分享

动漫头像数据集是用于研究和分析动漫头像相关问题的数据集&#xff0c;它包含了大量的动漫风格的头像图像。动漫头像是指以动漫风格绘制的虚构人物的头像图像&#xff0c;常见于动画、漫画、游戏等媒体。 数据集点击下载&#xff1a;YOLO动漫头像数据集50800图片.rar

mysql之host is blocked问题

程序上线一段时间之后&#xff0c;更新程序总是遇到这个问题 每次都是重启几次程序&#xff0c;或者执行 flush hosts; 毕竟指标不治本&#xff0c;抽出时间决定分析一下问题&#xff0c;查阅了几篇博客。&#xff08;感谢这几位大佬&#xff09; https://blog.51cto.com/u_…

SpringCloud学习笔记(二)_Eureka注册中心

一、Eureka简介 Eureka是一项基于REST&#xff08;代表性状态转移&#xff09;的服务&#xff0c;主要在AWS云中用于定位服务&#xff0c;以实现负载均衡和中间层服务器的故障转移。我们称此服务为Eureka Server。Eureka还带有一个基于Java的客户端组件Eureka Client&#xff…

入耳式无线耳机哪个款式好?无线蓝牙耳机音质排行榜

本着要买就认认真真的挑选一台的想法。和有线耳机相比&#xff0c;无线耳机确实有一定优势&#xff0c;比如说它的实用性明显要高不少。那么如何挑选&#xff0c;一款合适自己的耳机呢&#xff0c;首先&#xff0c;还是挑选出当前的热门款式&#xff0c;和各种网红推荐款&#…