0

我正在尝试从 fc.context 访问密钥,但不确定当我为函数 Compute 分配角色时可以从哪里获取密钥。我不想硬编码或将它们放入 ENV 中,而是希望通过将角色应用于函数计算来放入桶中。我已经将 s3 所有访问角色应用于 fc 但不知道如何放置?

- - 编码:utf-8 - -

# License: MIT
#

import logging
import oss2
import requests, io
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import urllib, base64
from dotenv import load_dotenv, find_dotenv
import os
from pathlib import Path  # Python 3.6+ only
env_path = Path('.') / '.env'
load_dotenv(find_dotenv())
# load_dotenv()

 
def handler(environ, start_response):
 # Enable logging
    logger = logging.getLogger()
    context = environ['fc.context']
    request_uri = environ['fc.request_uri']
    fig = plt.figure(figsize=(9, 6))
    x = np.linspace(0., 5., 100)
    y = np.sin(x)

    rows = 3
    columns = 2

    x = np.linspace(0., 5., 100)
    y = np.sin(x)

    grid = plt.GridSpec(rows, columns, wspace = .25, hspace = .25)

    plt.subplot(grid[:, 0])
    plt.annotate('sub1', xy = (0.5, -0.5), va = 'center', ha = 'center',  weight='bold', fontsize = 15)
    plt.plot(x, y)

    plt.subplot(grid[0, 1])
    plt.annotate('sub2', xy = (0.5, -0.5), va = 'center', ha = 'center',  weight='bold', fontsize = 15)
    plt.plot(x, y)

    plt.subplot(grid[1, 1])
    plt.annotate('sub3', xy = (0.5, -0.5), va = 'center', ha = 'center',  weight='bold', fontsize = 15)
    plt.plot(x, y)

    plt.subplot(grid[2, 1])
    plt.annotate('sub4', xy = (0.5, -0.5), va = 'center', ha = 'center',  weight='bold', fontsize = 15)
    fig = plt.gcf()

    plt.plot(x, y)
    buf = io.BytesIO()
    fig.savefig(buf, format='png')

    buf.seek(0)
    string = base64.b64encode(buf.read())

    uri = 'data:image/png;base64,' + urllib.parse.quote(string)
    BUCKET_NAME = 'Sample123'
    auth = oss2.Auth(Access_key, SecretKey)
    bucket = oss2.Bucket(auth, 'http://oss-cn-shenzhen.aliyuncs.com', BUCKET_NAME)
    IMAGE_NAME = 'SampleImage.png'
    bucket.put_object(IMAGE_NAME,buf.getvalue())
    # Last, return the final result
 
    status = '200 OK'
    response_headers = [('Content-type', 'image/png'), ('Content-Disposition', 'inline; filename="meme.jpeg"')]
    start_response(status, response_headers)
    return [ buf.getvalue() ]
   
4

1 回答 1

0

您可以从上下文中获取凭据并创建一个 oss 客户端,如下所示:

def get_oss_client(context, endpoint, bucket):
  creds = context.credentials
  if creds.security_token != None:
    auth = oss2.StsAuth(creds.access_key_id, creds.access_key_secret, creds.security_token)
  else:
    # for local testing, use the public endpoint
    endpoint = str.replace(endpoint, "-internal", "")
    auth = oss2.Auth(creds.access_key_id, creds.access_key_secret)
  return oss2.Bucket(auth, endpoint, bucket)
于 2021-01-05T05:40:50.200 回答