分享一个自己用得云函数代码

2023-04-27 09:52:50 浏览数 (1)

云函数端不到30行代码可匹配客户端request多种类型请求

代码语言:javascript复制
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
import urllib3

urllib3.disable_warnings()

def main_handler(event, context):
    try:
        args = eval(event['body'])
    except:
        return {"isBase64Encoded": False,
        "statusCode": 200,
        "headers": {'Content-Type': 'text/html; charset=utf-8'},
        "body": str(("error_body", str({'Content-Type': 'text/html; charset=utf-8'}), str(404), "", "utf-8"))}
    method, url, data, headers, cookies, files, auth, timeout, allow_redirects, hooks, stream, verify, cert, json = args
    try:
        html = requests.request(method, url, data=data, headers=headers, cookies=cookies, files=files, auth=auth, timeout=timeout, allow_redirects=allow_redirects, hooks=hooks, stream=stream, verify=verify, cert=cert, json=json)
        res = (str(html.text), str(html.headers), str(html.status_code), str(html.cookies), str(html.encoding))
        status_code = html.status_code
    except:
        status_code = 404
        res = ("timeout", str({'Content-Type': 'text/html; charset=utf-8'}), str(status_code), "", "utf-8")
    return {
        "isBase64Encoded": False,
        "statusCode": status_code,
        "headers": {'Content-Type': 'text/html; charset=utf-8'},
        "body": str(res)
    }

本地可通过python 请求接口部分代码

代码语言:javascript复制
# 使用云函数代理
    def yunProxy(self, method, url, data=None, headers=None, cookies=None, files=None, auth=None, timeout=time_out, allow_redirects=True, hooks=None, stream=None, verify=False, cert=None, json=None):
        yUrl = self.proxyList[random.randint(1, len(self.proxyList) - 1)].decode().strip()
        body = (method, url, data, headers, cookies, files, auth, timeout, allow_redirects, hooks, stream, verify, cert, json)
        try:
            html = requests.post(url=yUrl, data=str(body).encode('utf-8'), verify=False, timeout=20)
        except Exception as e:
            return None
        try:
            text, headers, status_code, cookies, htmlEncoding = eval(html.text)
        except Exception as e:
            text, headers, status_code, cookies, htmlEncoding = ("", {}, 200, "", "")
        res = Html(str(text), int(status_code), text.encode(), eval(headers), cookies, htmlEncoding)
        return res

0 人点赞