如何使用 Appengine 和来自 API 的 Python 脚本流数据将数据流式传输到 Google Cloud BigQuery?

How to stream data into Google Cloud BigQuery using Appengine with Python Script-flowing data from API?

我一直在尝试从下面 api 流式传输数据,但收效甚微。

https://dev.socrata.com/foundry/data.cityofchicago.org/8v9j-bter

main.py 脚本

       #install main packages
      !pip install sodapy
     import pandas as pd
     from sodapy import Socrata
     from google.datalab import Context

     #put into dataframe
     client = Socrata("data.cityofchicago.org", None)
     results = client.get("8v9j-bter", limit=2000)
     results_df = pd.DataFrame.from_records(results)

     #flow into BigQuery
     results_df.to_gbq('chicago_traffic.demo_data', Context.default().project_id,
                   chunksize=2000, verbose=True, if_exists='append')

App.yaml 脚本

     runtime: python27
      api_version: 1
     threadsafe: true

      handlers:
      - url: /.*
       script: main.app

cron.yaml 脚本

  cron:
     - description: "append traffic data"
      url: /.*
      target: main
      schedule: every 1 mins 
  retry_parameters:
     min_backoff_seconds: 2.5
     max_doublings: 5

requirements.txt

   pandas==0.22.0
   sodapy==1.4.6
   datalab==1.1.2
   google-api-python-client

您使用的 app.yaml 将部署在 App Engine Standard Enviroment. When you use the Standard Enviroment you can use any of these built-in third party libraries by adding them to your app.yaml file or you can use any other third-party library by following the steps in this link

这里的问题是previous link I shared中所述:

You can use third-party libraries that are pure Python code with no C extensions,

pandas 库的部分代码是用 C 语言编写的(https://pandas.pydata.org/#library-highlights ),因此为了使用 Pandas,您需要使用 App Engine Flexible Environment

您需要对文件进行一些修改才能部署到 运行。按照这些链接使您的文件适应灵活的环境:

!pip install sodapy 使用魔法命令 !, which is something exclusive from some Notebooks environments。您不能将该行添加到 main.py 文件中。此操作 (pip install sodapy) 将在应用程序部署期间 运行 因为您要将 sodapy==1.4.6 添加到 requirements.txt 文件中。

而不是添加 Context.default().project_id,您应该能够将 project_id 添加为 str。在 App Engine Flex 授权中 运行ning 应该不是问题。如果你想 运行 它在本地记得使用 a service account 与正确的权限。