from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from util.sessions import Session
class MainPage(webapp.RequestHandler):
def get(self):
session = Session()
if 'words' in session:
words = session['words']
else:
words = 'no words'
self.response.out.write('<html><body>')
self.response.out.write('<form action="/" method="post" enctype="multipart/form-data">')
self.response.out.write('Upload File: <input type="file" name="txt"><br>')
self.response.out.write('<input type="submit" name="submit" value="Submit">')
self.response.out.write(str(words))
self.response.out.write('</form>')
self.response.out.write('</body></html>')
class Study(webapp.RequestHanlder):
def post(self):
words = self.request.get('txt')
self.response.out.write(words)
application = webapp.WSGIApplication([('/', MainPage)],
('/study', Study)
], debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
2009년 12월 31일 목요일
구글 앱 엔진, 텍스트 파일 열기
2009년 12월 30일 수요일
python에서 html에서 읽어온 string 한글 검색
# -*- coding: utf-8 -*-
import urllib
import re
class MyOpener(urllib.FancyURLopener):
version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'
def Translate(eng):
urllib._urlopener = MyOpener()
f = urllib.urlopen('http://www.google.co.kr/dictionary?langpair=en|ko&q='+eng+'&hl=ko&aq=f')
html = f.read()
str = unicode('영어 > 한국어','euc-kr').encode('utf-8')
pos_ko = html.find(str)
str = unicode('영어 사전','euc-kr').encode('utf-8')
pos_en = html.find(str, pos_ko)
if __name__ == '__main__':
Translate('TEST')
2009년 12월 29일 화요일
Hello WebApp 분석
webapp
어플리케이션은 세가지 파트로 구성되어있다:
- 요구를 처리하고 반응하는 하나 혹은 그 이상의
RequestHandler
클래스 - URL 기반의 핸들러로 들어온 요구를 라우트하는
WSGIApplication
인스턴스 - CGI adaptor를 사용하여
WSGIApplication을 실행하는 메인 루틴
webapp
어플리케이션에 어울리게 기존의 helloworld.py 를 수정하여 다음과 같이 다시 코딩해보자:
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class MainPage(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('Hello, webapp World!')
application = webapp.WSGIApplication(
[('/', MainPage)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
run_wsgi_app(application)
Runs a WSGI application in App Engine's CGI environment. This is comparable to using a WSGI-to-CGI adaptor such as the one provided by the wsgiref
module of the Python standard library, but has several advantages: run_wsgi_app() automatically detects whether the application is running in the development server, and if so outputs errors to the browser in addition to the log. run_wsgi_app() also allows App Engine to send data output by the handler prior to the error, which wsgiref.handlers.CGIHandler
doesn't do.
Arguments:
- application
- A WSGI application object, such as webapp.WSGIApplication.
The WSGIApplication Class
The google.appengine.ext.webapp
package provides the following classes:
- class WSGIApplication(url_mapping, debug=False)
A WSGI-compatible application that maps URL paths to RequestHandler classes. An App Engine CGI script creates a WSGIApplication object, then runs it using a WSGI CGI handler such as run_wsgi_app().
Arguments:
- url_mapping
- A mapping of URL paths to request handlers, as a list of tuples where each tuple is a path-to-handler mapping. The first element of the tuple specifies the URL path as a string. The second element of the tuple is the constructor of a request handler class, a subclass of RequestHandler.
- debug
- If
True
, the application runs in "debug mode." Primarily, this means that the request handler's handle_exception() method is called with debug_mode=True
when the handler raises an exception, which prints debugging information to the web browser.
출처
- http://code.google.com/appengine/docs/python/gettingstarted/usingwebapp.html
- http://code.google.com/appengine/docs/python/tools/webapp/utilmodule.html#run_wsgi_app
- http://code.google.com/appengine/docs/python/tools/webapp/wsgiapplicationclass.html
2009년 11월 24일 화요일
앱 엔진 시작하기 start App Engine
application: wogud86
version: 1
runtime: python
api_version: 1
handlers:
- url: /.*
script: main.py
D:\AppEngine\HelloWorld에 파이썬 코드 넣기
#D:\AppEngine\HelloWorld
print 'Content-Type: text/plain'
print 'hello world'
app Engine 구동
command 창에 다음과 같이 입력 -> http://localhost:8080/ 접속하여 결과 확인
(명령이 끝나지 않고, 이 상태 에선 main.py수정 후 브라우저에서 새로고침 만으로 확인 가능)
command 창을 그대로 두고 main.py만을 수정하여 보자.
#D:\AppEngine\HelloWorld
import wsgiref.handlers
from google.appengine.ext import webapp
class MyHandler(webapp.RequestHandler):
def get(self):
self.response.out.write("hello!")
def main():
app = webapp.WSGIApplication([(r'.*', MyHandler)], debug=True)
wsgiref.handlers.CGIHandler().run(app)
if __name__ == '__main__':
main()
Hello World
#D:\AppEngine\HelloWorld
import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
class MyHandler(webapp.RequestHandler):
def get(self):
self.response.out.write(template.render('main.html',{}))
def main():
app = webapp.WSGIApplication([(r'.*', MyHandler)], debug=True)
wsgiref.handlers.CGIHandler().run(app)
if __name__ == '__main__':
main()
샘플 코드 많은 곳 : http://code.google.com/p/google-app-engine-samples/
구글 앱 엔진 소개 영상 Google App Engine
Introducing Google App Engine (pt. 2)
Introducing Google App Engine (pt. 3)
Introducing Google App Engine (pt. 4)
Introducing Google App Engine (pt. 5)
Introducing Google App Engine (pt. 6)
2009년 11월 17일 화요일
구글 사전 찾기
구글 번역기가 업데이트 되었기 때문이다.
대신에 구글 사전이 생겼는데 더 좋은 듯..
우선 대강 한글 정보 가져오기
# -*- coding: utf-8 -*-
import urllib
import re
class MyOpener(urllib.FancyURLopener):
version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'
def Translate(eng):
urllib._urlopener = MyOpener()
f = urllib.urlopen('http://www.google.co.kr/dictionary?langpair=en|ko&q='+eng+'&hl=ko&aq=f')
html = f.read()
pos1 = html.find('meta name="description" content=')
pos2 = html.find(eng, pos1)
pos3 = html.find('-', pos2)
file('search_html.txt', 'w').write(html)
return html[pos2:pos3]
if __name__ == '__main__':
kor = Translate('south')
file('Translate_result.txt', 'w').write(kor)
2009년 11월 14일 토요일
파이썬 URL 이미지 wxPython에 출력하기(print image from image by wxPython)
import wx
import urllib
class TestFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="LI")
p = wx.Panel(self)
data = urllib.urlopen("http://www.bigtravelweb.com/images/south_america_map_l.jpg")
img = wx.ImageFromStream(data, wx.BITMAP_TYPE_JPEG).ConvertToBitmap()
wx.StaticBitmap(p, -1, img, (10, 10), (img.GetWidth(), img.GetHeight()))
app = wx.PySimpleApp()
frm = TestFrame()
frm.Show()
app.MainLoop()
2009년 11월 13일 금요일
파이썬 구글 이미지 검색(python google image search)
import urllib
class MyOpener(urllib.FancyURLopener):
version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'
def image_addr(word):
urllib._urlopener = MyOpener()
f = urllib.urlopen('http://images.google.com/images?hl=ko&source=hp&q='+word+'&btnG=%EC%9D%B4%EB%AF%B8%EC%A7%80+%EA%B2%80%EC%83%89&gbv=2&aq=f&oq=')
extension = '.jpg'
html = f.read()
pos2 = html.find(extension)
pos1 = html[0:pos2].rfind('http://')
return html[pos1:pos2+len(extension)]
if __name__=='__main__':
print image_addr('south')