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

news2024/11/18 13:54:39

文章目录

  • 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 ET

data = '''
<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 ET

input = '''
<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 ET

input = '''
<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 json

data = '''
[
  { "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.coloradmin.cn/o/898883.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

all in one之安装docker、青龙和青龙卸载更新(第三章)

安装docker和青龙 ubuntu安装docker 参考教程0 参考教程1 参考教程2 apt-get install docker-ce docker-ce-cli containerd.io更改docker国内源 一、国内加速地址 Docker中国区官方镜像 https://registry.docker-cn.com网易 http://hub-mirror.c.163.comustc https://d…

Monitor.Analog采集软件详细设计说明

Monitor.Analog模拟量采集软件概要设计&#xff1a; 1. 引言&#xff1a; 模拟量采集软件的目标是实现对模拟量信号的采集、处理和展示。该软件旨在提供一个用户友好的界面&#xff0c;允许用户配置采集参数、实时监测模拟量信号&#xff0c;并提供数据分析和导出功能。 2. 功能…

多功能数据采集主机——数据集中采集

无论是机房监控系统还是仓库监控系统&#xff0c;又或者是其他大型场所的监控系统都会用的一个设备——多功能数据采集主机。 在环境监控系统中会用到温湿度、水浸、烟感等多种传感器&#xff0c;时时监测周围环境&#xff0c;这些传感器都可以通过多功能数据采集主机&#xff…

学习笔记230816---vue项目中使用第三方组件{el-dropdown}如何设置禁止事件功能

问题描述 使用第三方组件elementui&#xff0c;在导航菜单el-menu的el-menu-item中嵌入一个下拉菜框el-dropdown。点击...icon弹出下拉菜单el-dropdown-menu&#xff0c;那么这时会触发事件冒泡&#xff0c;el-menu-item菜单项的点击事件也会触发。 解决方法 阻止事件冒泡&am…

学习笔记230804---逻辑跳转this.$router.push在写法上的优化

今天和资深前端代码写重&#xff0c;同时写页面带参跳转&#xff0c;组长觉得他写的方式比我高端一点&#xff0c;我觉得确实是&#xff0c;像资深大佬学习。 我的写法&#xff1a; this.$router.push(/bdesign?applicationId${this.data.id}&appName${this.data.name})…

【单片机毕业设计4-基于stm32c8t6的红外测温系统】

【单片机毕业设计4-基于stm32c8t6的红外测温系统】 前言一、功能介绍二、硬件部分三、软件部分总结 前言 &#x1f525;这里是小殷学长&#xff0c;单片机毕业设计篇4基于stm32的红外测温系统 &#x1f9ff;创作不易&#xff0c;拒绝白嫖可私 一、功能介绍 -------------------…

mysql主从复制最简单环境搭建(一主一从)

提示&#xff1a;前面有相应的文章利用不同方式进行的主从配置 文章目录 前言一、概述二、主从复制的优点三、原理四、搭建五、主库配置六、从库配置七、测试 前言 一、概述 主从复制是指将主数据库的DDL 和 DML 操作通过二进制日志传到从库服务器中&#xff0c;然后在从库上…

Mac 使用 rar 命令行工具解压和压缩文件

在 Mac 中常遇到的压缩文件有 zip 和 rar 格式的&#xff0c;如果是 zip 格式的 Mac 系统默认双击一下文件就能直接解压了&#xff0c;但 rar 文件就不行。 需要额外下载 rar 工具了实现。 第一步&#xff1a;下载 rar 工具 工具网址&#xff1a;https://www.rarlab.com/dow…

【C++】stack/queue/优先级队列的模拟实现

目录 1. stack/queue1.1 模拟实现 2. 优先级队列2.1 模拟实现2.2 仿函数 1. stack/queue stack文档说明 queue文档说明 stack和queue被称为容器适配器。 容器适配器是什么&#xff1f; 它是一种特殊的容器类型&#xff0c;通过封装已有的容器类型来提供特定功能的接口函数&a…

探索1688 API的无限商机与应用

为了更好地满足用户需求&#xff0c;1688.com开放了丰富强大的API接口&#xff0c;使得开发者可以便捷地与平台进行集成&#xff0c;实现自动化的商务操作。 产品查询与筛选&#xff1a;通过调用1688 API&#xff0c;你可以根据自定义条件进行商品查询和筛选&#xff0c;获取符…

JAVA三种拦截方式

最近面试有遇到拦截方式的场景&#xff0c;结合网上xdm的代码整理了下&#xff0c;分为以下三种&#xff1a; java原生过滤器Filter、springMVC拦截器、aop切面 目录&#xff1a; 一、java原生过滤器Filter二、springMVC拦截器三、aop切面 一、java原生过滤器Filter package c…

C++初阶语法——new,delete开辟/销毁动态内存空间

前言&#xff1a;在C语言中&#xff0c;有malloc&#xff0c;realloc&#xff0c;calloc开辟动态内存空间&#xff0c;free销毁动态内存空间。而在C中&#xff0c;使用new开辟动态内存空间&#xff0c;delete销毁动态内存空间。不仅简化了操作&#xff0c;更为重要的是&#xf…

springcloud3 hystrix实现服务监控显示3(了解)

一 hystrix的服务监控调用 1.1 hystrix的服务监控调用 hystrix提供了准实时的监控调用&#xff08;hystrix dashbord&#xff09;&#xff0c;Hystrix 会持续的记录所有通过hystrix发送的请求的执行信息&#xff0c;并以统计报表和图形的形式展示给用户&#xff0c;包括每秒执…

在海外如何进行应用商店的关键词优化

分析市场&#xff0c;了解我们的应用类别&#xff0c;将我们的应用与竞争对手的优点和缺点进行比较&#xff0c;找到市场上的空白或所谓未满足的需求&#xff0c;并思考如何填补。 1、应用商店关键词优化。 关键词优化的目的是找到最相关的关键词 &#xff0c;并测试应用元数据…

菜鸟Vue教程 - 实现带国际化的注册登陆页面

初接触vue的时候觉得vue好难&#xff0c;因为项目中要用到&#xff0c;就硬着头皮上&#xff0c;慢慢的发现也不难&#xff0c;无外乎画个布局&#xff0c;然后通过样式调整界面。在通过属性和方法跟js交互。js就和我们写的java代码差不多了&#xff0c;复杂一点的就是引用这种…

PHP8的正则表达式-PHP8知识详解

在网页程序的时候&#xff0c;经常会有查找符合某些复杂规则的字符串的需求。正则表达式就是描述这些规则的工具。 正则表达式是把文本或者字符串按照一定的规范或模型表示的方法&#xff0c;经常用于文本的匹配操作。 例如&#xff1a;我们在填写手机号码的时候&#xff0c;…

LinkedBlockingQueue详解,深入探究LinkedBlockingQueue源码

目录 1、LinkedBlokingQueue是一个有界队列 2、LinkedBlokingQueue是一个单向队列 3、LinkedBlokingQueue中的非阻塞方法 4、LinkedBlokingQueue中的阻塞方法 LinkedBlockingQueue是通过ReentrantLock实现的&#xff08;有界/无界&#xff09;阻塞队列&#xff0c;在线程池…

PHP8的字符串操作3-PHP8知识详解

今天继续分享字符串的操作&#xff0c;前面说到了字符串的去除空格和特殊字符&#xff0c;获取字符串的长度&#xff0c;截取字符串、检索字符串。 今天继续分享字符串的其他操作。如&#xff1a;替换字符串、分割和合成字符串。 5、替换字符串 替换字符串就是对指定字符串中…

SUMO traci接口控制电动车前往充电站充电

首先需要创建带有停车位的充电站(停车场和充电站二合一)&#xff0c;具体参考我的专栏中其他文章。如果在仿真的某个时刻&#xff0c;希望能够控制电动车前往指定的充电站充电&#xff0c;并且在完成充电后继续前往车辆原来的目的地&#xff0c;那么可以使用以下API&#xff1a…

STM32 F103C8T6学习笔记8:0.96寸单色OLED显示屏显示字符

使用STM32F103 C8T6 驱动0.96寸单色OLED显示屏: OLED显示屏的驱动&#xff0c;在设计开发中OLED显示屏十分常见&#xff0c;因此今日学习一下。一篇文章从程序到显示都讲通。 文章提供源码、原理解释、测试工程下载&#xff0c;测试效果图展示。 目录 OLED驱动原理—IIC通信…