import textwrap import random import string from datetime import datetime from django.conf import settings import base64 import requests from io import BytesIO def print_roundtrip(response, *args, **kwargs): def format_headers(d): return '\n'.join(f'{k}: {v}' for k, v in d.items()) print(textwrap.dedent(''' ---------------- request ---------------- {req.method} {req.url} {reqhdrs} {req.body} ---------------- response ---------------- {res.status_code} {res.reason} {res.url} {reshdrs} {res.text} ''').format( req=response.request, res=response, reqhdrs=format_headers(response.request.headers), reshdrs=format_headers(response.headers), )) def ranstr(num): salt = ''.join(random.sample(string.ascii_lowercase + string.digits, num)) return salt def rannum(num): salt = ''.join(random.sample(string.digits, num)) return salt def timestamp_to_time(millis): """10位时间戳转换为日期格式字符串""" return datetime.fromtimestamp(millis) def convert_to_base64(path: str): """给定图片转base64 Args: path (str): 图片地址 """ if path.startswith('http'): # 如果是网络图片 return str(base64.b64encode(BytesIO(requests.get(url=path).content).read()), 'utf-8') else: with open(settings.BASE_DIR + path, 'rb') as f: return str(base64.b64encode(f.read()), 'utf-8') def p_in_poly(p, poly): px = p['x'] py = p['y'] flag = False i = 0 l = len(poly) j = l - 1 # for(i = 0, l = poly.length, j = l - 1; i < l; j = i, i++): while i < l: sx = poly[i]['x'] sy = poly[i]['y'] tx = poly[j]['x'] ty = poly[j]['y'] # 点与多边形顶点重合 if (sx == px and sy == py) or (tx == px and ty == py): return (px, py) # 判断线段两端点是否在射线两侧 if (sy < py and ty >= py) or (sy >= py and ty < py): # 线段上与射线 Y 坐标相同的点的 X 坐标 x = sx + (py - sy) * (tx - sx) / (ty - sy) # 点在多边形的边上 if x == px: return (px, py) # 射线穿过多边形的边界 if x > px: flag = not flag j = i i += 1 # 射线穿过多边形边界的次数为奇数时点在多边形内 return (px, py) if flag else 'out'