Serverless架構如何獲取用戶IP和歸屬地運營商

這幾天一直在想,經過Serverless
Framework作一些什麼事情,是有趣的,思前想後,決定作一個APICenter,基於騰訊雲Serverless架構,使用Serverless
Framework只作一個API市場。php

簡單又愉快的,創建一個Project,全程將會用Python3.6進行開發。html

同時,我也會將這個系列的項目開源到git

https://github.com/anycodes/S...​github.comgithub

廢話很少說,先來第一個有趣的API,獲取用戶IP和IP地址,經過搜索引擎,咱們能夠查看到本身的IP地址:編程

咱們能夠經過瀏覽器抓包,得到到這個請求的接口:json

經過對接口的精簡,能夠肯定,獲取個人IP地址的請求連接就是:api

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()

測試運行:架構

編寫Serverless Framework的Yaml:app

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,由於我已經提早創建了。接下來能夠部署:

完成部署,能夠看一下咱們的效果:

至此,咱們完成了IP查詢的小工具,固然,若是用戶主動查詢IP地址呢?咱們能夠對代碼進行改造:

Serverless.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地址

再次部署:

部署完成以後:

測試1:

測試2:

至此,咱們完成了咱們的第一個API:查詢IP地址


相關文章
相關標籤/搜索