简体   繁体   English

谷歌云平台 - 数据存储 - Python ndb API

[英]Google Cloud Platform - Datastore - Python ndb API

I recently started working with the Google Cloud Platform, more precisely, with the ndb-Datastore-API.我最近开始使用 Google Cloud Platform,更准确地说,是使用 ndb-Datastore-API。 I tried to use following tutorial ( https://github.com/GoogleCloudPlatform/appengine-guestbook-python.git ) to get used to the API.我尝试使用以下教程 ( https://github.com/GoogleCloudPlatform/appengine-guestbook-python.git ) 来习惯 API。

Unfortunately, I cannot figure out how to import the third party library tweepy into tweet.py.不幸的是,我无法弄清楚如何将第三方库 tweepy 导入 tweet.py。 Google Cloud does not support tweepy so that I had to include the library manually in a folder /lib. Google Cloud 不支持 tweepy,因此我必须手动将库包含在文件夹 /lib 中。 But how do I now import the installed tweepy (pip install -t lib tweepy)?但是我现在如何导入已安装的 tweepy(pip install -t lib tweepy)?

I basically just try to put an Entity in the Google Datastore but I cannot figure out what I did wrong.我基本上只是尝试将实体放入 Google 数据存储区,但我无法弄清楚我做错了什么。

tweet.py:推文.py:

    # [START imports]
from __future__ import absolute_import, print_function
import os
import urllib
from time import *
import jinja2
import webapp2
from google.appengine.api import users
from google.appengine.ext import ndb

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)
# [END imports]

# [START globalvar]
# Go to http://apps.twitter.com and create an app.
# The consumer key and secret will be generated for you after
consumer_key="KEY"
consumer_secret="SECRET"
# After the step above, you will be redirected to your app's page.
# Create an access token under the the "Your access token" section
access_token="TOKEN"
access_token_secret="SECRET"
# [END globalvar]

USERNAME = "@Seeed"

def getDate():
    # local Time
    lt = localtime()
    # get Date
    year, month, day = lt[0:3]
    date = "%02i.%02i.%04i" % (day,month,year)
    return date

# [START tweet_count_entity]
class TweetCount(ndb.Model):
    """A main model for representing an individual TweetCount entry."""
    date = ndb.DateProperty(auto_now_add=True)
    tweets = ndb.IntegerProperty(indexed=False)
    user_name = ndb.StringProperty(indexed=False)

# [END tweet_count_entity]

# [START tweet_counter]
class TweetCounter(webapp2.RequestHandler):
    """
    # Create a key for the Entity
    def tweetCount_key(date):
        date = getDate()
        return ndb.Key('TweetCount', date)"""

    # Get TweetCount for actor "user_name"
    def getTweetCount(self, user_name):
        auth = OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)
        api = tweepy.API(auth)
        user = api.get_user(user_name)
        return user.followers_count

    def get(self):
        count = self.getTweetCount(USERNAME)
        tweet_count_user_name = USERNAME
        tweet_count_tweets = count
        tweet_count = TweetCount(tweets=tweet_count_tweets, user_name=tweet_count_user_name)
        tweet_count.put()
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.write("" + USERNAME + " TweetCount: " + str(count))

# [END tweet_counter]

# [START app]
app = webapp2.WSGIApplication([
    ('/', TweetCounter),
], debug=True)
# [END app]

app.yaml:应用程序.yaml:

runtime: python27
api_version: 1
threadsafe: true

# [START handlers]
handlers:
- url: /.*
  script: tweet.app
# [END handlers]

# [START libraries]
libraries:
- name: webapp2
  version: latest
- name: jinja2
  version: latest
# [END libraries]

index.yaml:索引.yaml:

indexes:
- kind: TweetCount
  properties:
  - name: date
  - name: tweets
  - name: user_name

appengine_config.py: appengine_config.py:

from google.appengine.ext import vendor

# Add any libraries installed in the "lib" folder.
vendor.add('lib')

Thank you very much for your help.非常感谢您的帮助。 I appreciate any help and an explanation about what I did wrong.我感谢任何帮助和解释我做错了什么。

Based on your tweet.py and app.yaml , I can see the 2 things that may be the reason you cannot yet use tweepy in your Python application.根据您的tweet.pyapp.yaml ,我可以看到两件事可能是您还不能在 Python 应用程序中使用tweepy的原因。 For the sake of being through, I'll document the complete process.为了通过,我将记录完整的过程。

Acquire tweepy library获取tweepy库

As Tweepy is a third party library and not a library that ships with Google App Engine, we have to package it with our Python application as you've already suggested withpip install --target lib tweepy .由于Tweepy第三方库,而不是 Google App Engine 附带的库,因此我们必须将它与我们的 Python 应用程序一起打包,正如您已经通过pip install --target lib tweepy建议的pip install --target lib tweepy The directory specified after the --target option is where the third party library will be downloaded. --target选项后指定的目录是第三方库的下载目录。

Vendor in the third-party directory第三方目录中的供应商

Now that we've downloaded the third party library, Python must be made to search this lib directory when attempting to import modules.现在我们已经下载了第三方库,在尝试导入模块时,必须让 Python 搜索这个lib目录。 This can be done as you've shown, using an appengine_config.py file in your application directory as indicated in Installing a library like so:这可以按照您所展示的方式完成,使用应用程序目录中的appengine_config.py文件,如安装库中所示,如下所示:

from google.appengine.ext import vendor
vendor.add('lib')

Import third-party module in the application在应用程序中导入第三方模块

Python will now look in the lib directory when attempting to import modules. Python 现在将在尝试导入模块时查看lib目录。 Thus, we add our import statement where appropriate in our application code (eg: tweet.py ):因此,我们在应用程序代码中的适当位置添加我们的 import 语句(例如: tweet.py ):

import tweepy

This import is not currently found in your tweet.py example.此导入当前未在您的tweet.py示例中找到。

Ensure tweepy's dependencies are also imported确保 tweepy 的依赖项也被导入

Note that tweepy when imported will attempt to import the ssl module so it must be included in the libraries section of your app.yaml like so:请注意,导入tweepy将尝试导入ssl模块,因此它必须包含在app.yamllibraries部分中,如下所示:

libraries:
- name: ssl
  version: latest

This too, was not in your example app.yaml .这也不是在您的示例app.yaml

With the above, one should be able to successfully deploy a python GAE application which properly imports tweepy .有了上述内容,应该能够成功部署一个正确导入tweepy的 python GAE 应用程序。 Note that I've not actively tested any of tweepy 's features, but merely imported it successfully.请注意,我没有积极测试tweepy的任何功能,只是成功导入了它。 Should you be seeing any errors with the above examples, I would suggested also including the following in your question:如果您在上述示例中看到任何错误,我建议您在问题中也包含以下内容:

  • App Engine SDK version App Engine SDK 版本
  • Python version蟒蛇版
  • pip version点子版本
  • Stack trace of the error you are receiving when deploying or serving a HTTP response部署或提供 HTTP 响应时收到的错误的堆栈跟踪

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM