Git Product home page Git Product logo

fc-python-sdk's Introduction

Aliyun FunctionCompute Python SDK

https://travis-ci.org/aliyun/fc-python-sdk.svg?branch=master https://coveralls.io/repos/github/aliyun/fc-python-sdk/badge.svg?branch=master

Overview

The SDK of this version is dependent on the third-party HTTP library requests.

Running environment

Python 2.7, Python 3.6

> 其中 python2.7 支持到 2.5.0, 后续的版本不支持

Notice

fc and fc2 are not compatible, now master repo is fc2, if you still use fc, 1.x branch is what you need. We suggest using fc2, The main difference between fc and fc2 is:

1, all http request fuction can set headers

def invoke_function(self, serviceName, functionName, payload=None,
        headers = {'x-fc-invocation-type': 'Sync', 'x-fc-log-type' : 'None'}):
    ...

Attention: abandon async_invoke_function, there is only one function interface invoke_function, distinguish between synchronous and asynchronous by x-fc-invocation-type parameters(Sync or Async).

# sync invoke
client.invoke_function('service_name', 'function_name')

# async invoke
client.invoke_function('service_name', 'function_name', headers = {'x-fc-invocation-type': 'Async'})

2, The all http response returned by the user is the following object

class FcHttpResponse(object):
    def __init__(self, headers, data):
        self._headers = headers
        self._data = data

    @property
    def headers(self):
        return self._headers

    @property
    def data(self):
        return self._data

Note: for invoke function, data is bytes, for other apis, data is dict

Installation

Install the official release version through PIP (taking Linux as an example):

$ pip install aliyun-fc2

You can also install the unzipped installer package directly:

$ sudo python setup.py install

if you still use fc, you can install the official fc1 release version through PIP (taking Linux as an example):

$ pip install aliyun-fc

Getting started

# -*- coding: utf-8 -*-

import fc2


# To know the endpoint and access key id/secret info, please refer to:
# https://help.aliyun.com/document_detail/52984.html
client = fc2.Client(
    endpoint='<Your Endpoint>',
    accessKeyID='<Your AccessKeyID>',
    accessKeySecret='<Your AccessKeySecret>')

# Create service.
client.create_service('service_name')

# set vpc config when creating the service
vpcConfig = {
        'vpcId': '<Your Vpc Id>',
        'vSwitchIds': '<[Your VSwitch Ids]>',
        'securityGroupId': '<Your Security Group Id>'
}

# create vpcConfig when creating the service
# you have to set the role if you want to set vpc config
vpc_role = 'acs:ram::12345678:role/aliyunvpcrole'

# set nas config when creating the service
nasConfig = {
       "userId": '<The NAS file system user id>',
       "groupId": '<The NAS file system group id>',
       "mountPoints": [
            {
                "serverAddrserverAddr" : '<The NAS file system mount target>',
                "mountDir" : '<The mount dir to the local file system>',
            }
       ],
}

service = client.create_service(name, role=vpc_role, vpcConfig=vpcConfig, nasConfig=nasConfig)

# Create function.
# the current directory has a main.zip file (main.py which has a function of myhandler)
# set environment variables {'testKey': 'testValue'}
client.create_function('service_name', 'function_name', 'python3',  'main.my_handler', codeZipFile = 'main.zip', environmentVariables = {'testKey': 'testValue'})

# Create function with initailizer
# main.my_initializer is the entry point of initializer interface
client.create_function('service_name', 'function_name', 'python3',  'main.my_handler', "main.my_initializer", codeZipFile = 'main.zip', environmentVariables = {'testKey': 'testValue'})

# Invoke function synchronously.
client.invoke_function('service_name', 'function_name')

# Create trigger
# Create oss trigger
oss_trigger_config = {
        'events': ['oss:ObjectCreated:*'],
        'filter': {
            'key': {
                'prefix': 'prefix',
                'suffix': 'suffix'
            }
        }
}
source_arn = 'acs:oss:cn-shanghai:12345678:bucketName'
invocation_role = 'acs:ram::12345678:role/aliyunosseventnotificationrole'
client.create_trigger('service_name', 'function_name', 'trigger_name', 'oss',
                                                     oss_trigger_config, source_arn, invocation_role)

# Create log trigger
log_trigger_config = {
        'sourceConfig': {
            'logstore': 'log_store_source'
        },
        'jobConfig': {
            'triggerInterval': 60,
            'maxRetryTime': 10
        },
        'functionParameter': {},
        'logConfig': {
            'project': 'log_project',
            'logstore': 'log_store'
        },
        'enable': False
}
source_arn = 'acs:log:cn-shanghai:12345678:project/log_project'
invocation_role = 'acs:ram::12345678:role/aliyunlogetlrole'
client.create_trigger('service_name', 'function_name', 'trigger_name', 'oss',
                                                     log_trigger_config, source_arn, invocation_role)
# Create time trigger
time_trigger_config = {
        'payload': 'awesome-fc'
        'cronExpression': '0 5 * * * *'
        'enable': true
}
client.create_trigger('service_name', 'function_name', 'trigger_name', 'timer', time_trigger_config, '', '')

# Invoke a function with a input parameter.
client.invoke_function('service_name', 'function_name', payload=bytes('hello_world'))

# Read a image and invoke a function with the file data as input parameter.
src = open('src_image_file_path', 'rb') # Note: please open it as binary.
r = client.invoke_function('service_name', 'function_name', payload=src)
# save the result as the output image.
dst = open('dst_image_file_path', 'wb')
dst.write(r.data)
src.close()
dst.close()

# Invoke function asynchronously.
client.invoke_function('service_name', 'function_name', headers = {'x-fc-invocation-type': 'Async'})

# List services.
client.list_services()

# List functions with prefix and limit.
client.list_functions('service_name', prefix='the_prefix', limit=10)

# Delete service.
client.delete_service('service_name')

# Delete function.
client.delete_function('service_name', 'function_name')

Testing

To run the tests, please set the access key id/secret, endpoint as environment variables. Take the Linux system for example:

$ export ENDPOINT=<endpoint>
$ export ACCESS_KEY_ID=<AccessKeyId>
$ export ACCESS_KEY_SECRET=<AccessKeySecret>
$ export STS_TOKEN=<roleARN>

Run the test in the following method:

$ nosetests                          # First install nose

More resources

Contacting us

License

fc-python-sdk's People

Contributors

alifyb avatar arlenmbx avatar cici503 avatar hryang avatar lophygor avatar nerdyyatrice avatar ohyee avatar rocaltair avatar rockuw avatar rsonghuster avatar shuaichang avatar tw108174 avatar yinglixn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fc-python-sdk's Issues

异常中没有error message

client = fc.Client(
    endpoint='http://x.cn-hangzhou.fc.aliyuncs.com',
    accessKeyID='STS.CDAPSeNauw7um6H6jah1gx3hP',
    accessKeySecret='x',
    securityToken='')

try:
    resp = client.invoke_function('rockuw', 'hello-world')
except Exception as e:
    print 'error message: ', e.message # MESSAGE IS EMPTY!!!

关于Client类_do_request实现的问题

代码中其他的方法如invoke_function使用了_do_request作为发送请求的方法,当需要使用其他的发送http请求的方式的时候(如异步http,而不是用requests,或者改变发送请求的方式以提高性能)用户代码可以继承Client并实现自己的_do_request方法。但有个问题,就是在_do_request方法之外假定了_do_request方法返回的是一个requests中的Response实例,这样当用户想重载_do_request方法的时候,会发现到处都需要改,这里更好的做法是_do_request外部不要依赖特定的库的实例,数据以python的内置类型来返回,解除底层发送方法和其他方法的耦合。

一个小的设计问题带来了很大的使用成本,希望能够修改这个问题。

python3.6 使用 update_function 如果使用了 zipFile 参数会报错

堆栈错误如下

Traceback (most recent call last):
  File "deploy.py", line 33, in <module>
    client.update_function(service_name, "user_login", runtime="python2.7", handler="user.login", codeZipFile="code.zip")
  File "/Users/lifei/.pyenv/versions/3.6.0/lib/python3.6/site-packages/fc/client.py", line 442, in update_function
    r = self._do_request(method, path, headers, body=json.dumps(payload).encode('utf-8'))
  File "/Users/lifei/.pyenv/versions/3.6.0/lib/python3.6/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/Users/lifei/.pyenv/versions/3.6.0/lib/python3.6/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/Users/lifei/.pyenv/versions/3.6.0/lib/python3.6/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/Users/lifei/.pyenv/versions/3.6.0/lib/python3.6/json/encoder.py", line 180, in default
    o.__class__.__name__)
TypeError: Object of type 'bytes' is not JSON serializable

async_invoke_function

aliyun_fc2-2.0.3

Is async_invoke_function abandon?

I got error when using async_invoke_function while updating to fc2.
And found headers={'x-fc-invocation-type':'Async'} in site-packages/fc2/client.py.
Please update README.rst.

always get module is not callable error.

在mac os 10.15.7 下想试一下fc调用, 可是总是出现 typeError,不知是不是不兼容3.7.7呢?

(fc) promote:fc-python-sdk rui$ python
Python 3.7.7 (default, Apr 8 2020, 13:55:27)
[Clang 11.0.0 (clang-1100.0.33.17)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

import fc2
client = fc2.client(endpoint="https://隐藏.cn-shanghai.fc.aliyuncs.com", accessKeyID="隐藏", accessKeySecret="隐藏")
Traceback (most recent call last):
File "", line 1, in
TypeError: 'module' object is not callable

python环境如下:
(fc) promote:fc-python-sdk rui$ pip list
Package Version


aliyun-fc2 2.5.0
certifi 2020.6.20
chardet 3.0.4
idna 2.10
pip 20.0.2
requests 2.24.0
setuptools 46.1.1
urllib3 1.25.11
wheel 0.34.2
WARNING: You are using pip version 20.0.2; however, version 20.2.4 is available.
You should consider upgrading via the '/Users/rui/Documents/sandbox/venv/fc/bin/python -m pip install --upgrade pip' command.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.