我正在尝试做一个非常简单的 Python 网络服务。它使用 Flickr API 创建一个“photo.search”并返回标题和照片的 URL。
该网络服务将托管在 Google App Engine 上。
这就是我现在真正拥有的:
import webapp2
from urllib import urlencode, urlopen
from xml.dom import minidom
from google.appengine.api import urlfetch
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
data = _doget('flickr.photos.search', text='to_search', per_page='2')
self.response.write('Ok')
def _prepare_params(params):
for (key, value) in params.items():
if isinstance(value, list):
params[key] = ','.join([item for item in value])
return params
def _doget(method, auth=False, **params):
params = _prepare_params(params)
url = 'http://flickr.com/services/rest/?api_key=%s&method=%s&%s%s'% \
('stackoverflow_key', method, urlencode(params),
_get_auth_url_suffix(method, auth, params))
result = urlfetch.fetch(url)
minidom.parse(result.content)
return result
application = webapp2.WSGIApplication([
('/', MainPage),
], debug=True)
我是 Python 的初学者,所以如果我犯了大错,我深表歉意 :) 我尝试了几个不起作用的教程和示例代码。
导入导致 500 服务器错误
Error: Server Error
The server encountered an error and could not complete your request.
If the problem persists, please report your problem and mention this error message and the query that caused it.
有谁可以告诉我它有什么问题?
如果有人有可以解决问题的示例代码,那就太好了。
非常感谢您的宝贵时间!!:D
编辑 :
好吧,我改变了我的代码,它比以前更简单,用于测试:
import webapp2
from urllib import urlencode, urlopen
from xml.dom import minidom
from google.appengine.ext.webapp.util import run_wsgi_app
import hashlib
import os
HOST = 'http://api.flickr.com'
API = '/services/rest'
API_KEY = 'my_key'
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/html'
data = _doget('flickr.photos.search', auth=False, text='to_search', per_page='1')
if data:
self.response.write(data)
else:
self.response.write('Error')
def _doget(method, **params):
url = '%s%s/?api_key=%s&method=%s&%s&format=json'% \
(HOST, API, API_KEY, method, urlencode(params))
res = urlfetch.fetch(url).content
# Flickr JSON api returns not valid JSON, which wrapped with "jsonFlickrApi(...)", so we get rid of it.
if 'jsonFlickrApi(' in res:
return res[14:-1]
return json.loads(res)
application = webapp2.WSGIApplication([
('/', MainPage),
], debug=True)
当我复制/粘贴此网址时,它可以完美运行。我的目标是在 flickr 返回数据时返回数据。但仍然无法正常工作。甚至没有显示打印:(