GVKun编程网logo

如何在Google App Engine中包含第三方Python库?(谷歌应用第三方)

17

这篇文章主要围绕如何在GoogleAppEngine中包含第三方Python库?和谷歌应用第三方展开,旨在为您提供一份详细的参考资料。我们将全面介绍如何在GoogleAppEngine中包含第三方Py

这篇文章主要围绕如何在Google App Engine中包含第三方Python库?谷歌应用第三方展开,旨在为您提供一份详细的参考资料。我们将全面介绍如何在Google App Engine中包含第三方Python库?的优缺点,解答谷歌应用第三方的相关问题,同时也会为您带来Google+登录-服务器端流程-Python-Google App Engine、Oauth Aeoid Python Google App Engine Google文档、python – app-engine-patch已经死了.现在,在Google App Engine上使用Django的最佳方式是什么?、python – Google App Engine中模型的默认值的实用方法。

本文目录一览:

如何在Google App Engine中包含第三方Python库?(谷歌应用第三方)

如何在Google App Engine中包含第三方Python库?(谷歌应用第三方)

如何在Google App Engine中添加Google不提供的第三方python库?我正在尝试在Google App Engine中使用BeautifulSoup,但无法这样做。但是我的问题是我想在Google App Engine中使用的任何库。

答案1

小编典典

为了手动包括任何其他库,你必须将它们放在其中的目录中app.yaml。因此,例如,如果你具有以下结构:

hello├── libs│   └── bs4 ├── hello.py └── app.yaml

然后hello.py你必须将这两行放在文件的开头:

import syssys.path.insert(0, ''libs'')

完成此操作后,你将能够使用要放入该libs目录的任何第三方库。

例如:

from bs4 import BeautifulSoup

答案2

小编典典

Google为你的GAE项目中包含的第三方库提供了一种有据可查的方法。

请参阅Python 2.7 docs中库的“向应用程序添加第三方程序包”部分。

如果要包括其他纯Python第三方程序包,可以通过设置供应商来实现。供应商允许你将软件包安装到项目的子目录中,并将其包含在代码中。要使用供应商,请在项目的根目录中创建(或修改)appengine_config.py

from google.appengine.ext import vendor# Add any libraries installed in the "lib" folder.vendor.add(''lib'')

然后只需将所有库的源代码放在lib目录中

> pip install beautifulsoup4 -t lib

因此,你的项目目录结构如下所示:

project- lib  - bs4- your_code.py

这将允许你项目的源文件导入libs的程序包/模块,就像它们已添加到你的中一样PYTHON_PATH。例如:

# file: your_code.pyimport bs4  # no need for ''from lib import bs4''# do stuff with bs4...

你还可以通过执行以下命令轻松地从requirements.txt文件安装所有内容

pip install -t lib -r requirements.txt

Google+登录-服务器端流程-Python-Google App Engine

Google+登录-服务器端流程-Python-Google App Engine

我正在使用Flask在Google App
Engine上构建应用程序。我正在从https://developers.google.com/+/web/signin/server-side-
flow中描述的服务器端流程实现Google+登录。切换到App Engine之前,我的工作流程非常相似。从那时起,也许我引入了一个错误。也许这与我在App
Engine中的实施有关。

我相信Google登录流程重定向到的网址应具有GET参数集“ gplus_id”,但是,我没有收到此参数。

我有一个通过以下方式创建的登录按钮:

(function() {  var po = document.createElement(''script'');  po.type = ''text/javascript''; po.async = true;  po.src = ''https://plus.google.com/js/client:plusone.js?onload=render'';  var s = document.getElementsByTagName(''script'')[0];  s.parentNode.insertBefore(po, s);})();function render() {  gapi.signin.render(''gplusBtn'', {    ''callback'': ''onSignInCallback'',    ''clientid'': ''{{ CLIENT_ID }}'',    ''cookiepolicy'': ''single_host_origin'',    ''requestvisibleactions'': ''http://schemas.google.com/AddActivity'',    ''scope'': ''https://www.googleapis.com/auth/plus.login'',    ''accesstype'': ''offline'',    ''width'': ''iconOnly''  });}

在页面的javascript代码中,我具有启动流程的功能:

var helper = (function() {  var authResult = undefined;  return {    onSignInCallback: function(authResult) {      if (authResult[''access_token'']) {        // The user is signed in        this.authResult = authResult;        helper.connectServer();      } else if (authResult[''error'']) {        // There was an error, which means the user is not signed in.        // As an example, you can troubleshoot by writing to the console:        console.log(''GPlus: There was an error: '' + authResult[''error'']);      }      console.log(''authResult'', authResult);    },    connectServer: function() {      $.ajax({        type: ''POST'',        url: window.location.protocol + ''//'' + window.location.host + ''/connect?state={{ STATE }}'',        contentType: ''application/octet-stream; charset=utf-8'',        success: function(result) {          // After we load the Google+ API, send login data.          gapi.client.load(''plus'',''v1'',helper.otherLogin);        },        processData: false,        data: this.authResult.code,        error: function(e) {          console.log("connectServer: error: ", e);        }      });    }  }})();/** * Calls the helper method that handles the authentication flow. * * @param {Object} authResult An Object which contains the access token and *   other authentication information. */function onSignInCallback(authResult) {  helper.onSignInCallback(authResult);}

这将在“ /
connect”处启动流程(请参见以上文档中引用的步骤8 ):

@app.route(''/connect'', methods=[''GET'', ''POST''])def connect():    # Ensure that this is no request forgery going on, and that the user    # sending us this connect request is the user that was supposed to.    if request.args.get(''state'', '''') != session.get(''state'', ''''):        response = make_response(json.dumps(''Invalid state parameter.''), 401)        response.headers[''Content-Type''] = ''application/json''        return response    # Normally the state would be a one-time use token, however in our    # simple case, we want a user to be able to connect and disconnect    # without reloading the page.  Thus, for demonstration, we don''t    # implement this best practice.    session.pop(''state'')    gplus_id = request.args.get(''gplus_id'')    code = request.data    try:        # Upgrade the authorization code into a credentials object        oauth_flow = client.flow_from_clientsecrets(''client_secrets.json'', scope='''')        oauth_flow.redirect_uri = ''postmessage''        credentials = oauth_flow.step2_exchange(code)    except client.FlowExchangeError:        app.logger.debug("connect: Failed to upgrade the authorization code")        response = make_response(            json.dumps(''Failed to upgrade the authorization code.''), 401)        response.headers[''Content-Type''] = ''application/json''        return response    # Check that the access token is valid.    access_token = credentials.access_token    url = (''https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s''           % access_token)    h = httplib2.Http()    result = json.loads(h.request(url, ''GET'')[1])    # If there was an error in the access token info, abort.    if result.get(''error'') is not None:        response = make_response(json.dumps(result.get(''error'')), 500)        response.headers[''Content-Type''] = ''application/json''        return response    # Verify that the access token is used for the intended user.    if result[''user_id''] != gplus_id:        response = make_response(            json.dumps("Token''s user ID doesn''t match given user ID."), 401)        response.headers[''Content-Type''] = ''application/json''        return response    ...

但是,流程在处停止if result[''user_id''] !=gplus_id:,说“令牌的用户ID与给定的用户ID不匹配”。result[''user_id'']是有效的用户ID,但gplus_id没有。

该行gplus_id = request.args.get(''gplus_id'')期望GET args包含“ gplus_id”,但它们仅包含“
state”。我的javascript connectServer函数是否有问题?我应该在其中包括“
gplus_id”吗?当然我当时还不知道。或者是其他东西?

答案1

小编典典

与此问题p类似,我认为这是文档不完整/不是最新/不一致的问题。

凡https://developers.google.com/+/web/signin/server-side-
flow表明,gplus_id将在GET参数被退回,这不是我所用的流量的情况。

我在https://github.com/googleplus/gplus-quickstart-
python/blob/master/signin.py中找到了答案,其中包括以下代码段:

# An ID Token is a cryptographically-signed JSON object encoded in base 64.# Normally, it is critical that you validate an ID Token before you use it,# but since you are communicating directly with Google over an# intermediary-free HTTPS channel and using your Client Secret to# authenticate yourself to Google, you can be confident that the token you# receive really comes from Google and is valid. If your server passes the# ID Token to other components of your app, it is extremely important that# the other components validate the token before using it.gplus_id = credentials.id_token[''sub'']

Oauth Aeoid Python Google App Engine Google文档

Oauth Aeoid Python Google App Engine Google文档

我正在尝试在Google App Engine中为我的学校报纸完成一个故事分配系统.它将追踪作家的截止日期,允许作家收集故事,并对周故事进行“一目了然”的观察.我和我的合作伙伴正试图将它与我们的报纸Google Apps安装完全整合.哦,我们必须使用3条腿的Oauth,因为我们没有Google Apps Premier.

在那次努力中,我偶然发现了Aeoid并且能够按照说明进行联合登录工作.这很酷!

我遇到麻烦的地方是使用Oauth获取用户谷歌文档的列表.我在这里设置了一个测试页面:mustrun.cornellsun.com/test.它给了我错误 – 我已经将它们复制到这封邮件的底部.我不知道这是否与我的消费者秘密有关(我应该使用从谷歌市场获得的密钥?还是应该使用我从管理域页面获得的密钥?).现在我正在使用我从管理域页面获得的密钥

同样复杂的是,实际的appspot域是mustrun2sun [] .appspot [太新了不能发布多个链接] .com,但我在google应用程序中设置它,以便只有来自我的域的用户才能登录以便应用程序部署在我的域上. (应用程序部署为必须[]运行[].corn [] ellsun [].[] com&所有内容都指向它,即使在管理域中也是如此.)

我正在使用GDClient 2.0类,所以我很确定一切都应该按计划运行…即我没有使用旧的服务或任何东西.我用了[] p:/ [] / k [] ing [] yo-bachi.blog [] spot.c [] om / 2010/05 / gaego [] ogleoauth.ht [] ml作为一点点我的Oauth“舞蹈”的模板,因为谷歌的例子已经过时了使用旧的Google数据1.0库 – 我想.

我进入测试页面时遇到的错误是

Traceback (most recent call last):
  File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py",line 511,in __call__
    handler.get(*groups)
  File "/base/data/home/apps/mustrun2sun/1.341947133742569880/main.py",line 170,in get
    Feed = client.GetDocList(auth_token=gdata.gauth.AeLoad(users.get_current_user().user_id())) #auth_token=TOKEN
  File "/base/data/home/apps/mustrun2sun/1.341947133742569880/gdata/docs/client.py",line 141,in get_doclist
    auth_token=auth_token,**kwargs)
  File "/base/data/home/apps/mustrun2sun/1.341947133742569880/gdata/client.py",line 635,in get_Feed
    **kwargs)
  File "/base/data/home/apps/mustrun2sun/1.341947133742569880/gdata/client.py",line 308,in request
    response,Unauthorized)
Unauthorized: Unauthorized - Server responded with: 401,

此外,由于这对任何源代码都很难,下面是相关代码:

import gdata.auth
import gdata.gauth
import gdata.docs.client
import gdata.docs.data
import gdata.docs.service
import gdata.alt.appengine

from aeoid import middleware,users

class GetoauthToken(webapp.RequestHandler):
    def get(self):
        user_id = users.get_current_user().user_id()
        saved_request_token = gdata.gauth.AeLoad("tmp_"+user_id)
        gdata.gauth.AeDelete ("tmp_" + user_id)
        request_token = gdata.gauth.AuthorizeRequestToken(saved_request_token,self.request.uri)
        #upgrade the token
        access_token = client.GetAccesstoken(request_token)
        #save the upgraded token
        gdata.gauth.AeSave(access_token,user_id)
        self.redirect('/test')     

class Test(webapp.RequestHandler):
    def get(self):
        TOKEN = gdata.gauth.AeLoad(users.get_current_user().user_id())
        if TOKEN:
            client = gdata.docs.client.DocsClient(source=SETTINGS['APP_NAME'])
            client.auth_token = gdata.gauth.AeLoad(users.get_current_user().user_id()) #Could try to put back as TOKEN?

            self.response.out.write('moo baby')
            client.ssl = True
            Feed = client.GetDocList(auth_token=gdata.gauth.AeLoad(users.get_current_user().user_id())) #auth_token=TOKEN
            self.response.out.write(Feed)
            self.response.out.write('moo boobob')
            self.response.headers['Content-Type'] = 'text/plain'
            for entry in Feed.entry:
                self.response.out.writeln(entry.title.text)
        else:
            # Get unauthorized request token
            gdata.gauth.AeDelete(users.get_current_user().user_id())
            client = gdata.docs.client.DocsClient(source=SETTINGS['APP_NAME'])
            client.ssl = True # Force communication through HTTPS

            oauth_callback_url = ('http://%s/get_oauth_token' %
                                  self.request.host)

            request_token = client.GetoAuthToken(
                SETTINGS['ScopES'],oauth_callback_url,SETTINGS['CONSUMER_KEY'],consumer_secret=SETTINGS['CONSUMER_SECRET'])
            gdata.gauth.AeSave(request_token,"tmp_"+users.get_current_user().user_id())
            # Authorize request token
            domain = None#'cornellsun.com'
            self.redirect(str(request_token.generate_authorization_url(google_apps_domain=domain)))

我一直在网上寻找答案&我找不到一个.

最佳答案
我有一个工作的python App Engine应用程序,它使用OpenID和OAuth来获取你的谷歌联系人:

http://github.com/sje397/Chess

它运行于:

http://your-move.appspot.com

请注意,由于App Engine支持built-in OpenID,因此不再需要Aeoid.

python – app-engine-patch已经死了.现在,在Google App Engine上使用Django的最佳方式是什么?

python – app-engine-patch已经死了.现在,在Google App Engine上使用Django的最佳方式是什么?

app-engine-patch作者正式将这个精彩的项目标记为死了 on their website.去年很多人都问过在Google App Engine上运行Django的最佳方式是什么,并且人们一次又一次地指向app-engine -patch是要走的路.既然这个项目已经死了,我很乐意重温这个讨论,看看你们都会推荐什么.

旧的app-engine-patch网站引用了一个名为djangoappengine的不同项目.它侧重于在App Engine上使用Native Django,但这样做似乎限制了您使用App Engine所有功能的能力(例如其内置的用户模型).作为替代解决方案,您对此有何看法?

现在app-engine-patch已经死了,Google App Engine Helper For Django项目现在看起来更吸引人吗?

或者app-engine-patch仍然如此之大,以至于尽管它已经死了你仍会建议仍然使用它?

我目前有一个项目处于中间阶段,依赖于app-engine-patch,并且喜欢使用它到目前为止,但我害怕继续使用已经死亡的项目.如果您对现在最好的长期解决方案有何看法,我将不胜感激.谢谢!

最佳答案
对于特定时刻,应用引擎补丁可能是更安全的选择.虽然目前尚未得到积极支持,但它仍然很棒,因为它已经过更彻底的测试.如果您已准备好承担一些风险 – 请尝试使用新的djangoappengine django-nonrel(非关系数据库的本机django支持,主要是google datastore).这是我们将在一段时间内使用的选项,所以可能值得尝试一下而不是回头看.例如,app引擎补丁仅支持管理员中的~300个实体(即不利用1.3.1功能),而djangoappengine django-nonrel不再是问题. www.allbuttonspressed.com,一个app-engine-patch背后的人的网站,都是以这种新方式构建的,你可以获取网站骨架@ http://bitbucket.org/wkornewald/allbuttonspressed/的源代码.

祝好运!

python – Google App Engine中模型的默认值

python – Google App Engine中模型的默认值

是否可以为模型设置默认值?例如,从Appengine Documentation中考虑此模型
from google.appengine.ext import db

class Pet(db.Model):
    name = db.StringProperty(required=True)
    type = db.StringProperty(required=True,choices=set(["cat","dog","bird"]))
    birthdate = db.Dateproperty()
    weight_in_pounds = db.Integerproperty()
    spayed_or_neutered = db.Booleanproperty()
    owner = db.UserProperty(required=True)

我想将name的默认值设置为“Unnamed Pet”,因此如果用户不提供,则采用默认值.这可能吗?

PS:我希望这可以在模型类Pet本身中完成

解决方法

使用默认属性,例如
class Pet(db.Model):
    name = db.StringProperty(required=True,default="(unnamed)")

今天关于如何在Google App Engine中包含第三方Python库?谷歌应用第三方的讲解已经结束,谢谢您的阅读,如果想了解更多关于Google+登录-服务器端流程-Python-Google App Engine、Oauth Aeoid Python Google App Engine Google文档、python – app-engine-patch已经死了.现在,在Google App Engine上使用Django的最佳方式是什么?、python – Google App Engine中模型的默认值的相关知识,请在本站搜索。

本文标签: