前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >分享一个自己用得云函数代码

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

作者头像
纯情
发布2023-04-27 09:52:50
2070
发布2023-04-27 09:52:50
举报
文章被收录于专栏:纯情博客

云函数端不到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
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-07-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云函数
云函数(Serverless Cloud Function,SCF)是腾讯云为企业和开发者们提供的无服务器执行环境,帮助您在无需购买和管理服务器的情况下运行代码。您只需使用平台支持的语言编写核心代码并设置代码运行的条件,即可在腾讯云基础设施上弹性、安全地运行代码。云函数是实时文件处理和数据处理等场景下理想的计算平台。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档