python_flask / Common.py
bbqdennisEX's picture
-- Added call_get_api and call_post_api to Common
0ce5073
import os
import re
import json
import requests
from pathlib import Path
# Define Constants
IS_DEBUG = False
# Helper Functions
def debug_print(message):
if IS_DEBUG:
print(message)
# Public Functions
def to_camel_case(snake_str):
components = snake_str.split('_')
return ''.join(x.capitalize() for x in components)
def camel_to_snake(camel_case_string):
# 使用正则表达式将驼峰命名法转换为下划线命名法
snake_case_string = re.sub(r'(?<!^)(?=[A-Z])', '_', camel_case_string).lower()
return snake_case_string
def extract_class_name(file_relative_path):
file_name = os.path.basename(file_relative_path)
class_name = os.path.splitext(file_name)[0]
return to_camel_case(class_name)
def safe_get_value(dictionary, key):
value = None
if key in dictionary:
value = dictionary[key]
return value
def read_json_file(file_path):
"""
读取指定路径的 JSON 文件,并返回解析后的数据。
:param file_path: JSON 文件的路径
:return: 解析后的 JSON 数据
"""
try:
# 使用 pathlib 处理文件路径
path = Path(file_path)
# 确保文件存在
if not path.is_file():
raise FileNotFoundError(f"File not found: {file_path}")
# 读取文件内容
with path.open('r', encoding='utf-8') as file:
data = json.load(file)
return data
except Exception as e:
print(f"An error occurred: {e}")
return None
def call_api(url, data, is_post=True):
print(f"Calling API: {url} data: {data}")
headers = {'Content-Type': 'application/json'}
if is_post:
requests_method = requests.post
else:
requests_method = requests.get
response = requests_method(url, json=data, headers=headers)
return response.json()
def call_post_api(url, data):
"""
Sends a POST request to the specified URL with the given data.
:param url: The URL to which the POST request is sent
:param data: A dictionary containing the data to be sent in the POST request
:return: Response object from the POST request
"""
return call_api(url, data, is_post=True)
def call_get_api(url, data):
"""
Sends a GET request to the specified URL with the given data.
:param url: The URL to which the GET request is sent
:param data: A dictionary containing the data to be sent in the GET request
:return: Response object from the GET request
"""
return call_api(url, data, is_post=False)
def update_google_sheet(api_key, spreadsheet_id, range_name, values):
url = f'https://sheets.googleapis.com/v4/spreadsheets/{spreadsheet_id}/values/{range_name}?key={api_key}'
headers = {
'Content-Type': 'application/json'
}
params = {
'valueInputOption': 'RAW'
}
data = {
'range': range_name,
'majorDimension': 'ROWS',
'values': values
}
response = requests.put(url, headers=headers, params=params, data=json.dumps(data))
if response.status_code == 200:
print('Update successful')
else:
print(f'Failed to update sheet: {response.status_code}, {response.text}')