这几天一直在想,通过Serverless
Framework做一些什么事情,是有趣的,思前想后,决定做一个APICenter,基于腾讯云Serverless架构,使用Serverless
Framework只做一个API市场。
简单又愉快的,建立一个Project,全程将会用Python3.6进行开发。
image同时,我也会将这个系列的项目开源到
https://github.com/anycodes/ServerlessPracticegithub.com
废话不多说,先来第一个有趣的API,获取用户IP和IP地址,通过搜索引擎,我们可以查看到自己的IP地址:
image我们可以通过浏览器抓包,获得到这个请求的接口:
image通过对接口的精简,可以确定,获取我的IP地址的请求链接就是:
https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=192.168.1.1&co=&resource_id=6006
接下来,我们可以通过Python编程来做这个功能:
# -*- coding:utf-8 -*-
import urllib.request
import json
import uuid
def return_msg(error, msg):
return_data = {
"uuid": str(uuid.uuid1()),
"error": error,
"message": msg
}
print(return_data)
return return_data
def get_ip_addr(ip):
url = "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=%s&co=&resource_id=6006" % ip
ip_data = json.loads(urllib.request.urlopen(url=url).read().decode("gbk"))
if ip_data["data"] and len(ip_data["data"]) > 0:
return ip_data["data"][0]["location"]
else:
return False
def main_handler(event, context):
try:
user_ip = event["requestContext"]["sourceIp"]
location = get_ip_addr(user_ip)
if location:
return return_msg(False, {"ip": user_ip, "location": location})
else:
return return_msg(True, "未能正确获得到IP地址")
except Exception as e:
print(e)
return return_msg(True, "内部错误")
def test():
event = {
"requestContext": {
"serviceId": "service-f94sy04v",
"path": "/test/{path}",
"httpMethod": "POST",
"requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
"identity": {
"secretId": "abdcdxxxxxxxsdfs"
},
"sourceIp": "14.17.22.34",
"stage": "release"
},
"headers": {
"Accept-Language": "en-US,en,cn",
"Accept": "text/html,application/xml,application/json",
"Host": "service-3ei3tii4-251000691.ap-guangzhou.apigateway.myqloud.com",
"User-Agent": "User Agent String"
},
"body": "{\"test\":\"body\"}",
"pathParameters": {
"path": "value"
},
"queryStringParameters": {
"foo": "bar"
},
"headerParameters": {
"Refer": "10.0.2.14"
},
"stageVariables": {
"stage": "release"
},
"path": "/test/value",
"queryString": {
"foo": "bar",
"bob": "alice"
},
"httpMethod": "POST"
}
print(main_handler(event, None))
if __name__ == "__main__":
test()
测试运行:
image编写Serverless Framework的Yaml:
get_user_ip:
component: "@serverless/tencent-scf"
inputs:
name: myapi_get_user_ip
codeUri: ./get_user_ip
handler: index.main_handler
runtime: Python3.6
region: ap-beijing
description: 获取用户的IP相关信息
memorySize: 64
timeout: 2
events:
- apigw:
name: serverless
parameters:
serviceId: service-8d3fi753
environment: release
endpoints:
- path: /get_user_ip
description: 获取用户的IP相关信息
method: GET
enableCORS: true
我这里已经指定了一个APIGW,因为我已经提前建立了。接下来可以部署:
image完成部署,可以看一下我们的效果:
image至此,我们完成了IP查询的小工具,当然,如果用户主动查询IP地址呢?我们可以对代码进行改造:
imageServerless.yaml进行简单升级:
get_user_ip:
component: "@serverless/tencent-scf"
inputs:
name: myapi_get_user_ip
codeUri: ./get_user_ip
handler: index.main_handler
runtime: Python3.6
region: ap-beijing
description: 获取用户的IP相关信息
memorySize: 64
timeout: 2
events:
- apigw:
name: serverless
parameters:
serviceId: service-8d3fi753
environment: release
endpoints:
- path: /get_user_ip
description: 获取用户的IP相关信息
method: POST
enableCORS: true
param:
- name: ip
position: BODY
required: 'FALSE'
type: string
desc: ip地址
再次部署:
image部署完成之后:
测试1:
image测试2:
image至此,我们完成了我们的第一个API:查询IP地址
imageimage
网友评论