【问题标题】:Python - Create Json file in Cloud Storage with json parsingPython - 使用 json 解析在 Cloud Storage 中创建 Json 文件
【发布时间】:2019-05-20 18:03:21
【问题描述】:

我从 SQL Server 数据库中获取数据,并将数据保存到 json 格式的变量中。我当然想直接在云存储中创建一个 json 文件,而不必在我的本地机器上创建一个 json 文件。有可能吗?

我能够在本地计算机上创建一个 json 文件,但我想通过在脚本中创建一个 json 对象而不是在本地计算机上创建一个文件,然后直接在 Cloud Storage 中创建一个文件来忽略此步骤。

#Libraries
import io, json, codecs
import pyodbc
import logging
import os
import cloudstorage as gcs
import gcloud
from gcloud import storage
from google.cloud import bigquery
import pandas as pd
from gcloud.bigquery import SchemaField
import os
from googleapiclient import discovery

#Path variable
try:
    script_path = os.path.dirname(os.path.abspath(__file__)) + "/"
except:
    script_path = "C:\\Users\\userl\\Documents\\auth.json"

#Bigquery Credentials and settings
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = script_path 

db = pyodbc.connect("DRIVER={SQL Server};server=10.0.1.1;database=blablabla;uid=xpto;pwd=xxx")
cursor = db.cursor()
SQLview = 'select * from test'
result = cursor.execute(SQLview)

items = [dict(zip([key[0] for key in cursor.description], row)) for row in result]

json_file = json.dumps(items, ensure_ascii=False).encode('utf-8')


client = storage.Client(project='big-data')
bucket = client.get_bucket('big-data-bkt')
blob = bucket.blob(json_file)
with open('dict_obj.json', 'rb') as f:
    blob.upload_from_file(f)

【问题讨论】:

    标签: python json parsing google-cloud-storage


    【解决方案1】:

    有可能,您必须使用第三方 boto 客户端库插件,云存储也支持流传输。

    要执行流式上传,请使用以下代码:

    dst_uri = boto.storage_uri( + '/' + , 'gs')

    dst_uri.new_key().set_contents_from_stream()

    请查看此链接:

    https://cloud.google.com/storage/docs/streaming

    https://cloud.google.com/storage/docs/boto-plugin#streaming-transfers

    【讨论】:

      猜你喜欢
      • 2019-09-27
      • 2023-04-02
      • 2015-12-25
      • 1970-01-01
      • 1970-01-01
      • 2016-08-18
      • 2023-03-05
      • 1970-01-01
      相关资源
      最近更新 更多