【问题标题】:Creating a spell check, need to access words.txt in App Engine创建拼写检查,需要在 App Engine 中访问 words.txt
【发布时间】:2012-02-10 05:35:03
【问题描述】:

我正在创建一个用户可以输入一段文本的应用程序,我在该段落上运行拼写检查。通过打开包含我的字典的文件'words.txt',我已经在本地文档中很容易地实现了这一点。我试图弄清楚如何打开一个单词列表来实现我的拼写检查。

我的第一次尝试是将它作为静态文件放在我的目录中并获取该文件,但我不断收到错误。

这是我的文件:

app.yaml:

application: *******
version: 1
runtime: python
api_version: 1

handlers:

- url: /(.*\.txt)
  mime_type: text/plain
  static_files: static/\1
  upload: static/(.*\.txt)

- url: /.*
  script: helloworld.py

摘自 helloworld.py

import os
from google.appengine.ext.webapp import template
import cgi
import datetime
import urllib
import wsgiref.handlers
from google.appengine.api import urlfetch 

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

....

result=urlfetch.fetch(os.path.join(os.path.dirname(__file__),'words.txt'))
words=set(result.splitlines())

怎么了?我不断收到错误消息。

【问题讨论】:

标签: python google-app-engine


【解决方案1】:

您无法从代码中访问在 app.yaml 中定义为静态的文件。相反,要么删除静态映射,要么在代码中包含另一个副本。然后您可以使用以下方式访问该文件:

f = open('words.txt')
words = f.read()
f.close()

【讨论】:

  • 这似乎对我不起作用。我目前在同一个目录(项目)中有 4 个文件。但是当我使用这些行时,我得到一个页面(我也尝试在下一条评论中使用'./words.txt',但它也不起作用):Traceback(最近一次调用最后一次):IOError:[Errno 2]没有这样的文件或目录:'words.txt'
  • @Danny 你检查过当前路径是什么吗?是否符合您的预期?如果文件位于子目录中,您是否正确指定了路径?您还确定文件没有被 app.yaml 中的静态处理程序捕获吗?
【解决方案2】:

您在这里混合了许多不同的文件访问方法。当你在做:

result=urlfetch.fetch(os.path.join(os.path.dirname(__file__),'words.txt'))

如果您没有声明它是 static_files 的一部分,那么您为“words.txt”创建的路径将是您上传到与处理程序脚本相同目录中的文件的正确路径,尽管它看起来根据您的配置,您希望路径更像:

os.path.join(os.path.dirname(__file__), 'static', 'words.txt')

但是,这里有两个问题。首先,static_files 由与您的处理程序不同的进程提供服务,并且(可能)被加载到完全不同的服务器上。您将无法访问它们的文件系统(我想这就是您使用 urlfetch 的原因。)但是,您正在构建的路径是用于文件系统访问,而不是 urlfetch 访问。要在生产环境中使用 urlfetch,您需要使用网络 url,正如 @brianmichelich 所建议的那样——但是请注意,这在使用开发服务器时不起作用,它一次只能处理一个请求。

但是,如果您从 app.yaml 中删除静态指令,您应该能够将该路径用作常规 with/open 块的一部分。

【讨论】:

    【解决方案3】:

    您可以将本地文件放在 Google App Engine 上并打开它们以供阅读。
    如果您的文件位于顶层,您需要执行以下操作:

    f = open('./words.txt')
    

    您不需要使用 urlfetch 获取文件。

    【讨论】:

    【解决方案4】:

    您应该获取一个完全限定的网址,例如 http://myapp.appspot.com/words.txt

    from google.appengine.api import urlfetch, app_identity
    
    url = 'http://%s/words.txt' % app_identity.get_default_version_hostname()
    result=urlfetch.fetch(url)
    words=result.content
    

    【讨论】:

      猜你喜欢
      • 2015-08-22
      • 2015-06-12
      • 1970-01-01
      • 1970-01-01
      • 2011-09-09
      • 1970-01-01
      • 2011-02-15
      • 2012-08-15
      • 1970-01-01
      相关资源
      最近更新 更多