requests
GET
python
import requests
url ='https://finance.pae.baidu.com/vapi/stockshort'
params = {'code':'09888', 'market':'hk', 'finClientType':'pc' }
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, params=params, headers=headers)
print(response.status_code)
print(response.text)
POST
python
# 表单格式
import requests
url = 'https://example.com/api'
data = {'key1': 'value1', 'key2': 'value2'} # 表单数据
response = requests.post(url, data=data)
print(response.status_code)
print(response.json())
python
# json格式
import requests
url = 'https://example.com/api'
json_data = {'key1': 'value1', 'key2': 'value2'} # JSON 数据
headers = {'Content-Type': 'application/json'}
response = requests.post(url, json=data, headers=headers)
print(response.status_code)
print(response.json())
pymsql
python
import pymysql
from pymysql import cursors
class SQLHelper:
env = {
'host': 'localhost',
'user': 'root',
'password': 'ccc+022599',
'database': 'test'
}
@classmethod
def open(cls):
conn = pymysql.connect(host=cls.env['host'],
user=cls.env['user'],
password=cls.env['password'],
database=cls.env['database'])
cursor = conn.cursor(cursor= pymysql.cursors.DictCursor)
return conn, cursor
@staticmethod
def close(conn, cursor):
cursor.close()
conn.close()
@classmethod
def fetch_one(cls, sql, params):
conn, cursor = SQLHelper.open()
cursor.execute(sql, params)
result = cursor.fetchone()
SQLHelper.close(conn, cursor)
return result
@classmethod
def insert_many(cls, sql, params):
conn, cursor = SQLHelper.open()
try:
cursor.executemany(sql, params)
affected_rows = cursor.rowcount
conn.commit()
return affected_rows
except Exception as e:
conn.rollback()
print(e)
return 0
finally:
SQLHelper.close(conn, cursor)
python
if __name__ == '__main__':
arr = [
{'name':'ccb', 'age':25},
{'name':'ccb2', 'age':26}
]
sql = 'insert into emp (name, age) values (%s, %s)'
params = [(item['name'], item['age']) for item in arr ]
affected_rows = SQLHelper.insert_many(sql, params)
print(affected_rows)
logging
python
import logging
from logging.handlers import TimedRotatingFileHandler
# 配置日志记录器
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# 创建TimedRotatingFileHandler对象
handler = TimedRotatingFileHandler('app.log', when='midnight', interval=1, backupCount=7)
handler.suffix = '%Y-%m-%d'
handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
logger.addHandler(handler)
# 记录日志
logger.debug('这是一条DEBUG级别的日志')
logger.info('这是一条INFO级别的日志')