rocketMq之快速入門(二)
阿新 • • 發佈:2020-12-07
關於urlopen的補充
#處理get請求,不傳data,則為get請求
import urllib
from urllib.request import urlopen
from urllib.parse import urlencode
url='http://www.xxx.com/login'
data={"username":"admin","password":123456}
req_data=urlencode(data)#將字典型別的請求資料轉變為url編碼
res=urlopen(url+'?'+req_data)#通過urlopen方法訪問拼接好的url
res=res.read().decode()#read()方法是讀取返回資料內容,decode是轉換返回資料的bytes格式為str
print(res)
#處理post請求,如果傳了data,則為post請求
import urllib
from urllib.request import Request
from urllib.parse import urlencode
url='http://www.xxx.com/login'
data={"username":"admin","password":123456}
data=urlencode(data)#將字典型別的請求資料轉變為url編碼
data=data.encode('ascii')#將url編碼型別的請求資料轉變為bytes型別
req_data=Request(url,data)#將url和請求資料處理為一個Request物件,供urlopen呼叫
with urlopen(req_data) as res:
res=res.read().decode()#read()方法是讀取返回資料內容,decode是轉換返回資料的bytes格式為str
print(res)
時間和日期補充
常用時間處理方法
- 今天
today = datetime.date.today()
- 昨天
yesterday = today - datetime.timedelta(days=1)
- 上個月
last_month = today.month - 1 if today.month - 1 else 12
- 當前時間戳
time_stamp = time.time()
- 時間戳轉datetime
datetime.datetime.fromtimestamp(time_stamp)
- datetime轉時間戳
int(time.mktime(today.timetuple()))
- datetime轉字串
today_str = today.strftime("%Y-%m-%d")
- 字串轉datetime
today = datetime.datetime.strptime(today_str, "%Y-%m-%d")
- 補時差
today + datetime.timedelta(hours=8)
-
Python 計算笛卡爾積
計算多個集合的笛卡爾積,有規律可循,演算法和程式碼也不難,但是很多語言都沒有提供直接計算笛卡爾積的方法,需要自己寫大段大段的程式碼計算笛卡爾積,python 提供了一種最簡單的計算笛卡稱積的方法(只需要一行程式碼),詳見下面的程式碼:
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @file : Cartesian.py # @author : shlian # @date : 2018/5/29 # @version: 1.0 # @desc : 用python實現求笛卡爾積 import itertools class cartesian(object): def __init__(self): self._data_list=[] def add_data(self,data=[]): #新增生成笛卡爾積的資料列表 self._data_list.append(data) def build(self): #計算笛卡爾積 for item in itertools.product(*self._data_list): print(item) if __name__=="__main__": car=cartesian() car.add_data([1,2,3,4]) car.add_data([5,6,7,8]) car.add_data([9,10,11,12]) car.build()
計算的結果如下:
(1, 5, 9) (1, 5, 10) (1, 5, 11) (1, 5, 12) (1, 6, 9) (1, 6, 10) (1, 6, 11) (1, 6, 12) (1, 7, 9) (1, 7, 10) (1, 7, 11) (1, 7, 12) (1, 8, 9) (1, 8, 10) (1, 8, 11) (1, 8, 12) (2, 5, 9) (2, 5, 10) (2, 5, 11) (2, 5, 12) (2, 6, 9) (2, 6, 10) (2, 6, 11) (2, 6, 12) (2,