當前位置:首頁 » 編程語言 » pythonrei

pythonrei

發布時間: 2023-01-01 19:13:49

⑴ 老外人眼中,中國學生是怎麼樣的呀

卡羅琳•哈維來自辛巴威首都哈拉雷,現就讀於英威爾士大學。她說自己和中國學生算是「同在一個屋檐下」——同住的學生公寓樓里有5個中國人,從本科生到博士生一應俱全。「他們大都很友善,和其他國家學生沒什麼不同。一樣愛笑愛鬧,喜歡朋友聚會,噢,惟一不同就是他們都特別熱衷做菜!」(你的外國朋友是不是也在嘗過你做的菜後,邊點頭邊說:「Good,Good」?)她笑道,「他們真的特別厲害,每頓飯要做好幾盤菜,不像我,用一個盤子就解決了。」

說到適應新環境,她無奈地講述了全樓最嚴重的「中印危機」:一個中國女生每次都會在冰箱和櫥櫃里囤積很多食物,導致其他樓友沒地方存放食品。一個印度女生對此就特別有意見,經常抗議性地把中國女生的東西直接拿出來丟在外面。「這多幼稚啊,就像小孩子鬧脾氣。」卡羅琳嘆了口氣說道,「基本每次都是我去調停,感覺自己跟聯合國中印關系大使似的。

⑵ 如何用 flask 優雅的實現 restful api

首先,安裝Flask
pip install flask
閱讀這篇文章之前我假設你已經了解RESTful API的相關概念,如果不清楚,可以閱讀我之前寫的這篇博客[Designing a RESTful Web API
Flask是一個使用python開發的基於Werkzeug的Web框架。
Flask非常適合於開發RESTful API,因為它具有以下特點:
?使用Python進行開發,Python簡潔易懂
?容易上手
?靈活
?可以部署到不同的環境
?支持RESTful請求分發
我一般是用curl命令進行測試,除此之外,還可以使用Chrome瀏覽器的postman擴展。
資源
首先,我創建一個完整的應用,支持響應/, /articles以及/article/:id。
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
@app.route('/articles')
def api_articles():
return 'List of ' + url_for('api_articles')
@app.route('/articles/<articleid>')
def api_article(articleid):
return 'You are reading ' + articleid
if __name__ == '__main__':
app.run()
可以使用curl命令發送請求:
響應結果分別如下所示:
GET /
Welcome
GET /articles
List of /articles
GET /articles/123
You are reading 123
路由中還可以使用類型定義:
@app.route('/articles/<articleid>')
上面的路由可以替換成下面的例子:
@app.route('/articles/<int:articleid>')
@app.route('/articles/<float:articleid>')
@app.route('/articles/<path:articleid>')
默認的類型為字元串。
請求
請求參數
假設需要響應一個/hello請求,使用get方法,並傳遞參數name
from flask import request
@app.route('/hello')
def api_hello():
if 'name' in request.args:
return 'Hello ' + request.args['name']
else:
return 'Hello John Doe'
伺服器會返回如下響應信息:
GET /hello
Hello John Doe
GET /hello?name=Luis
Hello Luis
請求方法
Flask支持不同的請求方法:
@app.route('/echo', methods = ['GET', 'POST', 'PATCH', 'PUT', 'DELETE'])
def api_echo():
if request.method == 'GET':
return "ECHO: GET\n"
elif request.method == 'POST':
return "ECHO: POST\n"
elif request.method == 'PATCH':
return "ECHO: PACTH\n"
elif request.method == 'PUT':
return "ECHO: PUT\n"
elif request.method == 'DELETE':
return "ECHO: DELETE"
可以使用如下命令進行測試:
curl -X PATCH :5000/echo
不同請求方法的響應如下:
GET /echo
ECHO: GET
POST /ECHO
ECHO: POST
...
請求數據和請求頭
通常使用POST方法和PATCH方法的時候,都會發送附加的數據,這些數據的格式可能如下:普通文本(plain text), JSON,XML,二進制文件或者用戶自定義格式。
Flask中使用request.headers類字典對象來獲取請求頭信息,使用request.data 獲取請求數據,如果發送類型是application/json,則可以使用request.get_json()來獲取JSON數據。
from flask import json
@app.route('/messages', methods = ['POST'])
def api_message():
if request.headers['Content-Type'] == 'text/plain':
return "Text Message: " + request.data
elif request.headers['Content-Type'] == 'application/json':
return "JSON Message: " + json.mps(request.json)
elif request.headers['Content-Type'] == 'application/octet-stream':
f = open('./binary', 'wb')
f.write(request.data)
f.close()
return "Binary message written!"
else:
return "415 Unsupported Media Type ;)"
使用如下命令指定請求數據類型進行測試:
curl -H "Content-type: application/json" \
-X POST :5000/messages -d '{"message":"Hello Data"}'
使用下面的curl命令來發送一個文件:
curl -H "Content-type: application/octet-stream" \
-X POST :5000/messages --data-binary @message.bin
不同數據類型的響應結果如下所示:
POST /messages {"message": "Hello Data"}
Content-type: application/json
JSON Message: {"message": "Hello Data"}
POST /message <message.bin>
Content-type: application/octet-stream
Binary message written!
注意Flask可以通過request.files獲取上傳的文件,curl可以使用-F選項模擬上傳文件的過程。
響應
Flask使用Response類處理響應。
from flask import Response
@app.route('/hello', methods = ['GET'])
def api_hello():
data = {
'hello' : 'world',
'number' : 3
}
js = json.mps(data)
resp = Response(js, status=200, mimetype='application/json')
resp.headers['Link'] = 'http://luisrei.com'
return resp
使用-i選項可以獲取響應信息:
curl -i :5000/hello
返回的響應信息如下所示:
GET /hello
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 31
Link: http://luisrei.com
Server: Werkzeug/0.8.2 Python/2.7.1
Date: Wed, 25 Apr 2012 16:40:27 GMT
{"hello": "world", "number": 3}
mimetype指定了響應數據的類型。
上面的過程可以使用Flask提供的一個簡便方法實現:
from flask import jsonify
...
# 將下面的代碼替換成
resp = Response(js, status=200, mimetype='application/json')
# 這里的代碼
resp = jsonify(data)
resp.status_code = 200
狀態碼和錯誤處理
如果成功響應的話,狀態碼為200。對於404錯誤我們可以這樣處理:
@app.errorhandler(404)
def not_found(error=None):
message = {
'status': 404,
'message': 'Not Found: ' + request.url,
}
resp = jsonify(message)
resp.status_code = 404
return resp
@app.route('/users/<userid>', methods = ['GET'])
def api_users(userid):
users = {'1':'john', '2':'steve', '3':'bill'}
if userid in users:
return jsonify({userid:users[userid]})
else:
return not_found()
測試上面的兩個URL,結果如下:
GET /users/2
HTTP/1.0 200 OK
{
"2": "steve"
}
GET /users/4
HTTP/1.0 404 NOT FOUND
{
"status": 404,
"message": "Not Found: :5000/users/4"
}
默認的Flask錯誤處理可以使用@error_handler修飾器進行覆蓋或者使用下面的方法:
app.error_handler_spec[None][404] = not_found
即使API不需要自定義錯誤信息,最好還是像上面這樣做,因為Flask默認返回的錯誤信息是HTML格式的。
認證
使用下面的代碼可以處理 HTTP Basic Authentication。
from functools import wraps
def check_auth(username, password):
return username == 'admin' and password == 'secret'
def authenticate():
message = {'message': "Authenticate."}
resp = jsonify(message)
resp.status_code = 401
resp.headers['WWW-Authenticate'] = 'Basic realm="Example"'
return resp
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth:
return authenticate()
elif not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
接下來只需要給路由增加@require_auth修飾器就可以在請求之前進行認證了:
@app.route('/secrets')
@requires_auth
def api_hello():
return "Shhh this is top secret spy stuff!"
現在,如果沒有通過認證的話,響應如下所示:
GET /secrets
HTTP/1.0 401 UNAUTHORIZED
WWW-Authenticate: Basic realm="Example"
{
"message": "Authenticate."
}
curl通過-u選項來指定HTTP basic authentication,使用-v選項列印請求頭:
curl -v -u "admin:secret"
響應結果如下:
GET /secrets Authorization: Basic YWRtaW46c2VjcmV0
Shhh this is top secret spy stuff!
Flask使用MultiDict來存儲頭部信息,為了給客戶端展示不同的認證機制,可以給header添加更多的WWW-Autheticate。
resp.headers['WWW-Authenticate'] = 'Basic realm="Example"'resp.headers.add('WWW-Authenticate', 'Bearer realm="Example"')
調試與日誌
通過設置debug=True來開啟調試信息:
app.run(debug=True)
使用Python的logging模塊可以設置日誌信息:
import logging
file_handlewww.huashijixun.com?.ogging.FileHandler('app.log')
app.logger.addHandler(file_handler)
app.logger.setLevel(logging.INFO)
@app.route('/hello', methods = ['GET'])
def api_hello():
app.logger.info('informing')
app.logger.warning('warning')
app.logger.error('screaming bloody murder!')
return "check your logs\n"
CURL 命令參考
選項
作用
-X 指定HTTP請求方法,如POST,GET
-H 指定請求頭,例如Content-type:application/json
-d 指定請求數據
--data-binary 指定發送的文件
-i 顯示響應頭部信息
-u 指定認證用戶名與密碼
-v 輸出請求頭部信息

⑶ 橡皮的英文怎麼讀

「橡皮」的英文

  1. n.eraser英 [ɪ'reɪzə] 美 [ɪ'resɚ];

  2. rubber英 ['rʌbə] 美 ['rʌbɚ]

⑷ python求最大公約數和最小公倍數

不知道神馬叫輾轉相除法,直接用for:

#python3
importre
inp=input('Pleaseinputtwointegers:')
a,b=[int(i)foriinre.findall(r'd+',inp)]

defgys(m,n):
ifm==1orm==n:
returnm
foriinrange(min(m,n),0,-1):
ifm%i==0andn%i==0:
returni

g=gys(a,b)
print('最大公約數:',g)
print('最小公倍數:',a*b//g)
$python3gys.py
Pleaseinputtwointegers:9936
最大公約數:9
最小公倍數:396

⑸ python for循環提問

縮進都沒了,對於python來所沒法看啊。我猜一猜吧。

foriini2:
print(i)
x=i#i只是一個匹配的結果對吧,或者說一個字元串
...
i3=re.findall(r"("+str2+".*?"+str3+")",x,re.MULTILINE|re.DOTALL)#只匹配一個字元串
foryini3:#i3是只有一個元素的數組
print(y)#當然只有一行了

⑹ Markdown 替代品 Asciidoc 介紹

AsciiDoc,它的設計初衷就是為了解決寫書規模的問題,並且是 O』Reilly 的在線出版平台 Atlas 的推薦語言。經過一番學習,我覺得 Asciidoc 確實很適合電子書製作。

AsciiDoc 相比 Markdown 支持更多的格式,包括而不限於:

Markdown 通過自行擴展語法或者使用 HTML 可以實現這些格式,但前者造成文檔不通用的問題,後者則直接把展示結構硬編碼到了文檔中,將來修改會很麻煩。

當然, 更多的特性帶來更多的學習成本,對於博客等簡單文檔,這些特性並不是必須的,但對於電子書等大型文檔,標准內提供豐富的特性就很有必要,否則就需要自己實現不成熟、不兼容的擴展。

AsciiDoctor 是 AsciiDoc 的 Ruby 實現,也是一個工具鏈,實現了 AsciiDoc 對 HTML5/DocBook/EPUB/PDF/MOBI 的轉換(有的需要藉助第三方工具例如 Kindlegen)。相比原版 Python 實現,AsciiDoctor 作了以下改進:

AsciiDoctor 是一個很宏偉的項目,還有很多子項目在開發中,例如我比較關注的 Asciidoctor PDF 和 Asciidoctor EPUB3,這兩個項目用於去掉現有工具鏈中對 DocBook 的依賴,由原文檔直譯目標文檔。工具鏈層次的減少可以增加定製便利性,也更方便用戶安裝。

示例一:
https://raw.githubusercontent.com/asciidoctor/asciidoctor/master/README-zh_CN.adoc

示例二:
https://raw.githubusercontent.com/spring-guides/gs-gradle/master/README.adoc

[推薦] Visual Studio Code 和配套asciidoctor-vscode插件
https://marketplace.visualstudio.com/items?itemName=joaompinto.asciidoctor-vscode

asciidoctor 官網
https://github.com/asciidoctor/asciidoctor

asciidoc 官網
http://asciidoc.org/asciidocapi.html

AsciiDoc 簡介
https://chloerei.com/2014/10/16/asciidoc-introction/

asciidoctor-vscode插件的 Github 地址
https://github.com/asciidoctor/asciidoctor-vscode

⑺ Python任意輸入兩個數,求兩個數的最大公約數(最大公約數條件是公約數

# 定義一個函數
def hcf(x, y):
"""該函數返回兩個數的最大公約數"""

# 獲取最小值
if x > y:
smaller = y
else:
smaller = x

for i in range(1,smaller + 1):
if((x % i == 0) and (y % i == 0)):
hcf = i

return hcf

# 用戶輸入兩個數字
num1 = int(input("輸入第一個數字: "))
num2 = int(input("輸入第二個數字: "))

print( num1,"和", num2,"的最大公約數為", hcf(num1, num2))

⑻ 誰是足球史上最偉大的球員

貝利
艾迪遜·阿蘭蒂斯·德·納西曼托(Edson Arantes do Nascimento),1940年10月23日出生於巴西[1] ,巴西著名足球運動員,綽號「貝利」(Pelé)[1] 。貝利出生於巴西的一個貧寒家庭 ,是二十世紀最偉大的體育明星之一,在足壇有「球王」(O Rei do futebol)之稱。貝利被譽為是現代足球歷史上最偉大的球員。貝利在球場上司職前鋒和攻擊型前衛, 22年職業生涯共打進1283個進球(非邀請賽進球757個 )。貝利在1958、1962、1970年世界盃均隨巴西隊奪得冠軍,從而幫助祖國永久保存雷米特金杯,是唯一一位三次獲得世界盃冠軍的球員。 同時他也率領桑托斯足球俱樂部在1962和1963年兩次奪得南美解放者杯和洲際杯冠軍。 1961年,貝利被巴西總統雅尼奧·奎德羅斯宣布為「不可對外出口的國寶」。 1974年10月,貝利宣布退役 。1975年6月,貝利復出為美國紐約宇宙足球俱樂部效力,1977年10月,貝利正式宣布退役 。
1987年6月他被授予國際足聯金質勛章,1999年被國際奧運委員會(IOC)選舉為「世紀最佳運動員」 。2000年被《法國足球》金球獎得主評為世紀最佳球員 ,同年和馬拉多納一起被授予FIFA世紀最佳球員稱號 。2004年FIFA國際足聯百年慶典他與「足球皇帝」貝肯鮑爾共同獲得FIFA百年最佳球員和足球名人大獎。 並被美國《時代周刊》列入「20世紀最具影響力的100個人物」。
2012年,金足獎授予貝利「史上最佳球員獎」, 2013年國際足聯頒獎典禮上,貝利被授予榮譽金球獎。

⑼ 新手提問 python for循環問題 print (y) #這里為什麼只輸出一行

有一種可能,i3的長度就是1,所以for循環裡面只有一行輸出結果

⑽ 新手求助 python input

import re
i1 = open('test.txt','r').read()
str_input = input("please input:")
i2 = re.findall(r"%s(.*?)hi"$str_input, i1, re.MULTILINE | re.DOTALL)
for i in i2:
print (i)
我沒實驗,你先看看行不行

熱點內容
sql2008錯誤233 發布:2025-07-03 02:28:52 瀏覽:168
創建資料庫語句mysql 發布:2025-07-03 02:14:34 瀏覽:146
python量化投資 發布:2025-07-03 02:05:11 瀏覽:804
proxy代理伺服器地址 發布:2025-07-03 01:56:52 瀏覽:910
ps選區存儲 發布:2025-07-03 01:55:21 瀏覽:842
sql2008連接數 發布:2025-07-03 01:55:20 瀏覽:246
androidstring 發布:2025-07-03 01:53:55 瀏覽:183
密碼sql注入 發布:2025-07-03 00:44:07 瀏覽:555
oa伺服器需要什麼硬體 發布:2025-07-03 00:36:05 瀏覽:512
4mol的naoh怎麼配置 發布:2025-07-03 00:19:10 瀏覽:856