问题描述

首先,有名为 campsites.json 的JSON数据文件,数据格式为

{
"type": "FeatureCollection",
"name": "DOC_Campsites",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{
"type": "Feature",
"properties": {
"OBJECTID": 54996,
"name": "Rarangi Campsite",
"place": "Blenheim area",
"region": "Marlborough",
"introduction": "Camp next to the beach. Fish, walk, picnic, or simply sit and enjoy the roar of the waves.",
"campsiteCategory": "Standard",
"status": "OPEN",
"numberOfPoweredSites": 0,
"numberOfUnpoweredSites": 55,
"bookable": "No",
"free": null,
"facilities": "Water supply",
"activities": null,
"dogsAllowed": "Dogs with a DOC permit only",
"landscape": "Coastal",
"access": "Campervan, Car, Caravan",
"hasAlerts": "Refer to DOC website for current alerts",
"introductionThumbnail": "https://www.doc.govt.nz/thumbs/large/link/1b698c516b714b63b30de03203738e17.jpg",
"staticLink": "https://www.doc.govt.nz/link/f5c4e8776bee486aaa1ae8ebdc1e48f8.aspx",
"locationString": "Located in Blenheim area",
"x": 1687530,
"y": 5417097,
"assetId": 100030520,
"dateLoadedToGIS": "2021-05-28T04:15:08Z",
"GlobalID": "{C02F0A50-9316-459A-ADD9-93518E6677EA}"
},
"geometry": {"type": "Point","coordinates": [174.04700047400002,-41.39289982899993]}
}
, ... ...
]
}

全部的campsites.json文件内容下载地址:https://files.cnblogs.com/files/lulight/campsites.json?t=1655124060

修改下面的 server3.py 文件,以达到目标:当用户在浏览器中输入带有区域名称(例如 http://localhost:8080/Marlborough)的 URL 时,这个python服务器应该查询 region=Marlborough 的区域中的 Campsite category 类别为“Great Walk”的 Name +  staticLink 数据在页面中

server3.py 文件内容:

#Author: Sunil Lal

#This is a simple HTTP server which listens on port 8080, accepts connection request, and processes the client request
#in sepearte threads. It implements basic service functions (methods) which generate HTTP response to service the HTTP requests.
#Currently there are 3 service functions; default, welcome and getFile. The process function maps the requet URL pattern to the service function.
#When the requested resource in the URL is empty, the default function is called which currently invokes the welcome function.
#The welcome service function responds with a simple HTTP response: "Welcome to my homepage".
#The getFile service function fetches the requested html or img file and generates an HTTP response containing the file contents and appropriate headers. #To extend this server's functionality, define your service function(s), and map it to suitable URL pattern in the process function. #This web server runs on python v3
#Usage: execute this program, open your browser (preferably chrome) and type http://servername:8080
#e.g. if server.py and broswer are running on the same machine, then use http://localhost:8080 from socket import *
import _thread serverSocket = socket(AF_INET, SOCK_STREAM) serverPort = 8080
serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serverSocket.bind(("", serverPort)) serverSocket.listen(5)
print('The server is running')
# Server should be up and running and listening to the incoming connections #Extract the given header value from the HTTP request message
def getHeader(message, header): if message.find(header) > -1:
value = message.split(header)[1].split()[0]
else:
value = None return value #service function to fetch the requested file, and send the contents back to the client in a HTTP response.
def getFile(filename): try: # open and read the file contents. This becomes the body of the HTTP response
f = open(filename, "rb") body = f.read() header = ("HTTP/1.1 200 OK\r\n\r\n").encode() except IOError: # Send HTTP response message for resource not found
header = "HTTP/1.1 404 Not Found\r\n\r\n".encode()
body = "<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n".encode() return header, body #service function to generate HTTP response with a simple welcome message
def welcome(message): header = "HTTP/1.1 200 OK\r\n\r\n".encode()
body = ("<html><head></head><body><h1>Welcome to my homepage</h1></body></html>\r\n").encode() return header, body #default service function
def default(message): header, body = welcome(message) return header, body #We process client request here. The requested resource in the URL is mapped to a service function which generates the HTTP reponse
#that is eventually returned to the client.
def process(connectionSocket) :
# Receives the request message from the client
message = connectionSocket.recv(1024).decode() if len(message) > 1: # Extract the path of the requested object from the message
# Because the extracted path of the HTTP request includes
# a character '/', we read the path from the second character
resource = message.split()[1][1:] #map requested resource (contained in the URL) to specific function which generates HTTP response
if resource == "":
responseHeader, responseBody = default(message)
elif resource == "welcome":
responseHeader,responseBody = welcome(message)
else:
responseHeader,responseBody = getFile(resource) # Send the HTTP response header line to the connection socket
connectionSocket.send(responseHeader)
# Send the content of the HTTP body (e.g. requested file) to the connection socket
connectionSocket.send(responseBody)
# Close the client connection socket
connectionSocket.close() #Main web server loop. It simply accepts TCP connections, and get the request processed in seperate threads.
while True: # Set up a new connection from the client
connectionSocket, addr = serverSocket.accept()
#Clients timeout after 60 seconds of inactivity and must reconnect.
connectionSocket.settimeout(60)
# start new thread to handle incoming request
_thread.start_new_thread(process,(connectionSocket,))

问题解答

server3.py 文件中,实现了默认Defaultwelcome 和 getFile 方法,当访问URL为 http://localhost:8080 时,调用default方法,输出 Welcome to my homepage 信息。同理,当访问URL为  http://localhost:8080/welcome 时,调用welcome方法,同样输出 Welcome to my homepage 信息。 而 getFile 方法,则是读取指定的文件,输出文件内容。所以,本题最重要的代码部分为 getFile方法实现。

当用户在浏览器中输入带有区域名称(例如 http://localhost:8080/Marlborough)的 URL 时,这个python服务器应该查询 region=Marlborough 的区域中的 Campsite category 类别为“Great Walk”的 Name +  staticLink 数据在页面中

第一步:引入 JSON 包

import json

第二步:定义 region 和 campsiteCategory的过滤条件 condition1 和 condition2,以及指定filename为 campsites.json (因为这里只是完成题目,所以硬编码在代码中)

        filename = "campsites.json"
condition1 = "Marlborough"
condition2 = "Basic" # "Great Walk"

第三步:开始使用Json.load文件中的数据,把内容转换为 dict对象,然后根据 JSON格式,读取 features 列表,通过for 循环来一条一条的判断 condtion1 和 condition 2,满足条件,通过html拼接为一个Table

def getFile(regionname):

    try:
filename = "campsites.json"
condition1 = "Marlborough"
condition2 = "Basic" # "Great Walk"
# open and read the file contents. This becomes the body of the HTTP response
f = open(filename, "rb")
jdata = json.load(f) # 查询region=Marlborough的区域中的Campsite category类别为“Great Walk”的Name , site总数并返回
# region=Marlborough
## campsiteCategory =="Great Walk"; # print(jdata['name']);
# print(jdata['features'][1]['properties']['region'])
# print(type(jdata['features'][1])) outputTable = ""
index = 0
for fs in jdata['features']:
if fs['properties']['region'] == condition1 and fs['properties']['campsiteCategory'] == condition2:
outputTable += "<tr><td>" + \
fs['properties']['name']+"</td><td>" + \
fs['properties']['staticLink']+"</td></tr>"
# print(fs['properties']['campsiteCategory'])
index += 1 body = ("<html><head></head><body><h1>Welcome to my homepage</h1><br><h2>Total row is " +
str(index)+"</h2><br><table>"+outputTable+"</table></body></html>\r\n").encode() header = ("HTTP/1.1 200 OK\r\n\r\n").encode() except IOError: # Send HTTP response message for resource not found
header = "HTTP/1.1 404 Not Found\r\n\r\n".encode()
body = "<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n".encode() return header, body

第四步:运行 python server3.py, 检验结果

> python server3.py

因为 campsites.json 数据源中,没有同时满足 region =="Marlborough"  和 campsiteCategory =="Great Walk" 的数据。

所以为了展示页面效果,修改了过滤条件为:

def getFile(regionname):

    try:
filename = "campsites.json"
condition1 = regionname; # "Marlborough"
condition2 = "Basic" # "Great Walk"

再次测试的效果如下:

【END】

附录:完整的Server3.py 代码

# Author: Sunil Lal

# This is a simple HTTP server which listens on port 8080, accepts connection request, and processes the client request
# in sepearte threads. It implements basic service functions (methods) which generate HTTP response to service the HTTP requests.
# Currently there are 3 service functions; default, welcome and getFile. The process function maps the requet URL pattern to the service function.
# When the requested resource in the URL is empty, the default function is called which currently invokes the welcome function.
# The welcome service function responds with a simple HTTP response: "Welcome to my homepage".
# The getFile service function fetches the requested html or img file and generates an HTTP response containing the file contents and appropriate headers. # To extend this server's functionality, define your service function(s), and map it to suitable URL pattern in the process function. # This web server runs on python v3
# Usage: execute this program, open your browser (preferably chrome) and type http://servername:8080
# e.g. if server.py and broswer are running on the same machine, then use http://localhost:8080 from socket import *
import _thread
import json serverSocket = socket(AF_INET, SOCK_STREAM) serverPort = 8080
serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serverSocket.bind(("", serverPort)) serverSocket.listen(5)
print('The server is running')
# Server should be up and running and listening to the incoming connections # Extract the given header value from the HTTP request message def getHeader(message, header): if message.find(header) > -1:
value = message.split(header)[1].split()[0]
else:
value = None return value # service function to fetch the requested file, and send the contents back to the client in a HTTP response. def getFile(regionname): try:
filename = "campsites.json"
condition1 = regionname; # "Marlborough"
condition2 = "Basic" # "Great Walk"
# open and read the file contents. This becomes the body of the HTTP response
f = open(filename, "rb")
#body = f.read()
jdata = json.load(f) # 查询region=Marlborough的区域中的Campsite category类别为“Great Walk”的Name , site总数并返回
# region=Marlborough
## campsiteCategory =="Great Walk"; # print(jdata['name']);
# print(jdata['crs']);
# print(jdata['features'][1]['properties']['region'])
# print(jdata['features'][1]['properties']['campsiteCategory'])
# print(type(jdata['features'][1])) outputTable = ""
index = 0
for fs in jdata['features']:
if fs['properties']['region'] == condition1 and fs['properties']['campsiteCategory'] == condition2:
outputTable += "<tr><td>" + \
fs['properties']['name']+"</td><td>" + \
fs['properties']['staticLink']+"</td></tr>"
# print(index)
# print(fs['properties']['region'])
# print(fs['properties']['campsiteCategory'])
index += 1
#d = filter(lambda x:x.index)
#print(outputTable)
body = ("<html><head></head><body><h1>Welcome to my homepage</h1><br><h2>Total row is " +
str(index)+"</h2><br><table>"+outputTable+"</table></body></html>\r\n").encode() header = ("HTTP/1.1 200 OK\r\n\r\n").encode() except IOError: # Send HTTP response message for resource not found
header = "HTTP/1.1 404 Not Found\r\n\r\n".encode()
body = "<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n".encode() return header, body # service function to generate HTTP response with a simple welcome message def welcome(message): header = "HTTP/1.1 200 OK\r\n\r\n".encode()
body = ("<html><head></head><body><h1>Welcome to my homepage</h1></body></html>\r\n").encode() return header, body # default service function def default(message): header, body = welcome(message) return header, body # We process client request here. The requested resource in the URL is mapped to a service function which generates the HTTP reponse
# that is eventually returned to the client.
def process(connectionSocket):
# Receives the request message from the client
message = connectionSocket.recv(1024).decode() if len(message) > 1: # Extract the path of the requested object from the message
# Because the extracted path of the HTTP request includes
# a character '/', we read the path from the second character
resource = message.split()[1][1:] # map requested resource (contained in the URL) to specific function which generates HTTP response
if resource == "":
responseHeader, responseBody = default(message)
elif resource == "welcome":
responseHeader, responseBody = welcome(message)
else:
responseHeader, responseBody = getFile(resource) # Send the HTTP response header line to the connection socket
connectionSocket.send(responseHeader)
# Send the content of the HTTP body (e.g. requested file) to the connection socket
connectionSocket.send(responseBody)
# Close the client connection socket
connectionSocket.close() # Main web server loop. It simply accepts TCP connections, and get the request processed in seperate threads.
while True: # Set up a new connection from the client
connectionSocket, addr = serverSocket.accept()
# Clients timeout after 60 seconds of inactivity and must reconnect.
connectionSocket.settimeout(60)
# start new thread to handle incoming request
_thread.start_new_thread(process, (connectionSocket,))

参考资料

...

【Azure Developer】Python 读取 json文件及过滤出需要的结果的更多相关文章

  1. python读取json文件

    比如下图json数据,场景需要读取出wxid这项数据,然后传给后面的函数去使用 具体的脚本为 import json f =open('d:\\1024.json',encoding='utf-8') ...

  2. python读取json文件制作股票价格走势

  3. Python 读取json文件

    创建json文件: { "fontFamily": "微软雅黑", "fontSize": 12, "BaseSettings&q ...

  4. python读取json文件并解析

    # -*- coding: utf-8 -*- import os import json import sys reload(sys) sys.setdefaultencoding('utf-8') ...

  5. 【JSON】Python读取JSON文件报错json.decoder.JSONDecodeError的问题

    报错 json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line * column * ...

  6. 接口自动化(三)--读取json文件中的数据

    上篇讲到实际的请求数据放置在json文件内,这一部分记述一下python读取json文件的实现. 代码如下(代码做了简化,根据需要调优:可做一些容错处理): 1 import json 2 3 cla ...

  7. Python json 读取 json 文件并转为 dict

    Python json 读取 json 文件并转为 dict 在 D 盘 新建 test.json: { "test": "测试\n换行", "dic ...

  8. python中读取json文件报错,TypeError:the Json object must be str, bytes or bytearray,not ‘TextIOWrapper’

    利用python中的json读取json文件时,因为错误使用了相应的方法导致报错:TypeError:the Json object must be str, bytes or bytearray,n ...

  9. Python实现读取json文件到excel表

    一.需求 1.'score.json' 文件内容: { "1":["小花",99,100,98.5], "2":["小王" ...

  10. python学习笔记十六:读取JSON文件

    读取JSON文件可以用JSON库,示例代码: #coding:utf-8 import json with open("msg.json") as jsonfile: json_d ...

随机推荐

  1. k8s的内部服务通信

    首先看看 k8s 集群中内部各个服务互相访问的方法 Cluster IP Kubernetes以Pod作为应用部署的最小单位.Kubernetes会根据Pod的声明对其进行调度,包括创建.销毁.迁移. ...

  2. 1.10 内存ShellCode注入与格式化

    ShellCode 的格式化与注入功能在实战应用中也尤为重要,格式化Shellcode是指将其转换为可执行的二进制格式,使其能够在内存中运行.注入Shellcode是指将格式化的Shellcode注入 ...

  3. CSS概念与CSS选择器

    CSS简述 CSS被称为级联样式表或者CSS样式表.CSS也是一种标记语言. CSS主要用于设置HTML页面中的: 1.文本内容(字体,大小,对齐方式等), 2.图片的外形(宽高,边框样式,边距等), ...

  4. Win12不会取代Win11!真正目标是Google

    Windows 11之后自然应该是Windows 12,但这一次不太一样. 据多个消息源确认,Windows的下一个重大版本将不会是Windows 11的直接升级版,而是更专注于云和Web,同时大力接 ...

  5. Web入门:JavaScript文字动画

    欢迎来的我的小院,恭喜你今天又要涨知识了! 案例内容 利用JavaScript实现文字逐步展现的动画效果. 演示 学习 <!DOCTYPE html> <html lang=&quo ...

  6. 内存泄漏定位工具之 mtrace(二)

    1 前言 mtrace(memory trace),是 GNU Glibc 自带的内存问题检测工具,它可以用来协助定位内存泄露问题.它的实现源码在glibc源码的malloc目录下,其基本设计原理为设 ...

  7. CentOS 安装字体

    问题来源,今天服务端生成中文图片验证码的Base64字符串,结果返回到客户端后,解码Base64发现是乱码,怀疑是Centos 系统不包含中文字体的问题, 安装字体后,果然问题解决了,以后做系统镜像的 ...

  8. 致敬英雄,共悼逝者,css 让页面变黑白

    壹 ❀ 引 今天是四月四日清明节,也是全国哀悼抗疫烈士的一天.细心的同学可以发现,不仅是娱乐活动以及游戏全部停止,当我们打开各大门户网站,网站页面也都变成了黑白,那么具体怎么做呢,这里可以借用CSS3 ...

  9. NC19989 [HAOI2012]容易题(EASY)

    题目链接 题目 题目描述 为了使得大家高兴,小Q特意出个自认为的简单题(easy)来满足大家,这道简单题是描述如下: 有一个数列A已知对于所有的A[i]都是1~n的自然数,并且知道对于一些A[i]不能 ...

  10. IPFS Gateway Selector IPFS下载网关选择工具

    简介 用IPFS作文件分享可以覆盖很多场景, 现在IPFS网关也相当多了, 但是因为国内网络的状况, 不同网关在不同网络运营商的表现差别很大, 导致你提供的下载链接在对方那里可能速度很慢, 甚至无法访 ...