在无服务器上处理没有WSGI的ApiGateway事件时,无法响应很长的json

2024-06-03 15:24:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个lambda,在这里我将接收ApiGateway事件并用 一个非常长的JSON数组。你知道吗

它使用psycopg2查询数据库上的单个表,将其序列化为json并返回它。你知道吗

我决定不使用WSGI,因为任务很简单,所以我只返回一个 具有状态码的对象。你知道吗

这是密码

import json
import os

import psycopg2
import psycopg2.extras

from datetime import date
from json import dumps

def connection_params():
    try:
        system_variables = ['dbname', 'user', 'password', 'host', 'port']
        connection_params = {k: os.environ[k] for k in system_variables}
    except KeyError as e:
        raise KeyError('Variable not found', e)
    return connection_params

def dump(event, context):
    with psycopg2.connect(**connection_params(),
        cursor_factory=psycopg2.extras.RealDictCursor) as con:

        cur = con.cursor()
        cur.execute('select * from <table>;')
        return {
            'statusCode': 200,
            'body': dumps(cur.fetchall(), default=str)

我试着把cur.fetchall()改成cur.fetchone(),结果成功了 在转储fetchall时出现问题。你知道吗

以下是调试处于活动状态的无服务器输出:

$ SLS_DEBUG=true sls offline 
Serverless: Load command interactiveCli
Serverless: Load command config
Serverless: Load command config:credentials
Serverless: Load command config:tabcompletion
Serverless: Load command config:tabcompletion:install
Serverless: Load command config:tabcompletion:uninstall
Serverless: Load command create
Serverless: Load command install
Serverless: Load command package
Serverless: Load command deploy
Serverless: Load command deploy:function
Serverless: Load command deploy:list
Serverless: Load command deploy:list:functions
Serverless: Load command invoke
Serverless: Load command invoke:local
Serverless: Load command info
Serverless: Load command logs
Serverless: Load command metrics
Serverless: Load command print
Serverless: Load command remove
Serverless: Load command rollback
Serverless: Load command rollback:function
Serverless: Load command slstats
Serverless: Load command plugin
Serverless: Load command plugin
Serverless: Load command plugin:install
Serverless: Load command plugin
Serverless: Load command plugin:uninstall
Serverless: Load command plugin
Serverless: Load command plugin:list
Serverless: Load command plugin
Serverless: Load command plugin:search
Serverless: Load command config
Serverless: Load command config:credentials
Serverless: Load command rollback
Serverless: Load command rollback:function
Serverless: Load command offline
Serverless: Load command offline:start
Serverless: Load command login
Serverless: Load command logout
Serverless: Load command generate-event
Serverless: Load command test
Serverless: Load command dashboard
Serverless: Invoke offline
Serverless: Starting Offline: dev/us-east-1.
[offline] options: { apiKey: 'd41d8cd98f00b204e9800998ecf8427e',
  cacheInvalidationRegex: /node_modules/,
  corsAllowOrigin: [ '*' ],
  corsAllowCredentials: true,
  corsAllowHeaders: [ 'accept', 'content-type', 'x-api-key', 'authorization' ],
  corsExposedHeaders: [ 'WWW-Authenticate', 'Server-Authorization' ],
  disableCookieValidation: false,
  enforceSecureCookies: false,
  exec: '',
  hideStackTraces: false,
  host: 'localhost',
  httpsProtocol: '',
  location: '.',
  noAuth: false,
  noEnvironment: false,
  noTimeout: false,
  port: 3000,
  prefix: '/',
  preserveTrailingSlash: false,
  printOutput: false,
  providedRuntime: '',
  showDuration: false,
  stage: 'dev',
  region: 'us-east-1',
  resourceRoutes: false,
  skipCacheInvalidation: false,
  useSeparateProcesses: false,
  websocketPort: 3001,
  corsConfig: 
   { credentials: true,
     exposedHeaders: [ 'WWW-Authenticate', 'Server-Authorization' ],
     headers: [ 'accept', 'content-type', 'x-api-key', 'authorization' ],
     origin: [ '*' ] } }
[offline] funOptions {
  "funName": "dump_stores",
  "funTimeout": 30000,
  "handlerName": "dump",
  "handlerPath": "/Users/wviana/iVendas/Repos/dados-lojas-ivendas/ivendas_lojas_dump/handler",
  "runtime": "python3.7"
} 

[offline] dump_stores runtime python3.7
Serverless: Routes for dump_stores:
Serverless: GET /
[offline] Response Content-Type  application/json
Serverless: POST /{apiVersion}/functions/ivendas_lojas_dump-dev-dump_stores/invocations

Serverless: Offline [HTTP] listening on http://localhost:3000
Serverless: Enter "rp" to replay the last request

Serverless: GET / (λ: dump_stores)
[offline] requestId: ck2xiphr50000vbz3gfqxbucq
[offline] contentType: application/json
[offline] requestTemplate: 
[offline] payload: null
[offline] Invalidating cache...
[offline] Loading handler... (/Users/wviana/iVendas/Repos/dados-lojas-ivendas/ivendas_lojas_dump/handler)
[offline] event: { body: null,
  headers: 
   { Host: 'localhost:3000',
     'User-Agent': 'curl/7.64.1',
     Accept: '*/*' },
  httpMethod: 'GET',
  multiValueHeaders: 
   { Host: [ 'localhost:3000' ],
     'User-Agent': [ 'curl/7.64.1' ],
     Accept: [ '*/*' ] },
  multiValueQueryStringParameters: null,
  path: '/',
  pathParameters: null,
  queryStringParameters: null,
  requestContext: 
   { accountId: 'offlineContext_accountId',
     apiId: 'offlineContext_apiId',
     authorizer: 
      { principalId: 'offlineContext_authorizer_principalId',
        claims: undefined },
     httpMethod: 'GET',
     identity: 
      { accountId: 'offlineContext_accountId',
        apiKey: 'offlineContext_apiKey',
        caller: 'offlineContext_caller',
        cognitoAuthenticationProvider: 'offlineContext_cognitoAuthenticationProvider',
        cognitoAuthenticationType: 'offlineContext_cognitoAuthenticationType',
        cognitoIdentityId: 'offlineContext_cognitoIdentityId',
        cognitoIdentityPoolId: 'offlineContext_cognitoIdentityPoolId',
        sourceIp: '127.0.0.1',
        user: 'offlineContext_user',
        userAgent: 'curl/7.64.1',
        userArn: 'offlineContext_userArn' },
     protocol: 'HTTP/1.1',
     requestId: 'offlineContext_requestId_ck2xiphr80001vbz3e10y1u3u',
     requestTimeEpoch: 1573663652893,
     resourceId: 'offlineContext_resourceId',
     resourcePath: '/',
     stage: 'dev' },
  resource: '/',
  stageVariables: null,
  isOffline: true }
[offline] _____ CALLING HANDLER _____
Proxy Handler could not detect JSON: Serverless: Load command interactiveCli

Proxy Handler could not detect JSON: Serverless: Load command config

Proxy Handler could not detect JSON: Serverless: Load command config:credentials

Proxy Handler could not detect JSON: Serverless: Load command config:tabcompletion

Proxy Handler could not detect JSON: Serverless: Load command config:tabcompletion:install

Proxy Handler could not detect JSON: Serverless: Load command config:tabcompletion:uninstall

Proxy Handler could not detect JSON: Serverless: Load command create

Proxy Handler could not detect JSON: Serverless: Load command install

Proxy Handler could not detect JSON: Serverless: Load command package

Proxy Handler could not detect JSON: Serverless: Load command deploy

Proxy Handler could not detect JSON: Serverless: Load command deploy:function
Serverless: Load command deploy:list

Proxy Handler could not detect JSON: Serverless: Load command deploy:list:functions

Proxy Handler could not detect JSON: Serverless: Load command invoke

Proxy Handler could not detect JSON: Serverless: Load command invoke:local

Proxy Handler could not detect JSON: Serverless: Load command info
Serverless: Load command logs
Serverless: Load command metrics
Serverless: Load command print
Serverless: Load command remove
Serverless: Load command rollback
Serverless: Load command rollback:function
Serverless: Load command slstats
Serverless: Load command plugin
Serverless: Load command plugin
Serverless: Load command plugin:install
Serverless: Load command plugin
Serverless: Load command plugin:uninstall
Serverless: Load command plugin
Serverless: Load command plugin:list
Serverless: Load command plugin
Serverless: Load command plugin:search
Serverless: Load command config
Serverless: Load command config:credentials

Proxy Handler could not detect JSON: Serverless: Load command rollback

Proxy Handler could not detect JSON: Serverless: Load command rollback:function

Proxy Handler could not detect JSON: Serverless: Load command offline

Proxy Handler could not detect JSON: Serverless: Load command offline:start

Proxy Handler could not detect JSON: Serverless: Load command login

Proxy Handler could not detect JSON: Serverless: Load command logout

Proxy Handler could not detect JSON: Serverless: Load command generate-event

Proxy Handler could not detect JSON: Serverless: Load command test

Proxy Handler could not detect JSON: Serverless: Load command dashboard

Proxy Handler could not detect JSON: Serverless: Invoke invoke:local

[offline] _____ HANDLER RESOLVED _____
Serverless: Failure: {
    "statusCode": 200,
    "body": "<json_text>"
}
[offline] Using response 'default'
[offline] _____ RESPONSE PARAMETERS PROCCESSING _____
[offline] Found 0 responseParameters for 'default' response
[offline] headers {}
[offline] requestId: ck2xiphr50000vbz3gfqxbucq
Serverless: Got SIGINT signal. Offline Halting...
Serverless: Halting offline server

Tags: configjsonfalsenotloaddumpplugincommand