2009년 12월 31일 목요일

구글 앱 엔진, 텍스트 파일 열기


하드의 텍스트 파일을 열어서 스트링 혹은 데이터를 가져올때 예제 코드



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월 30일 수요일

python에서 html에서 읽어온 string 한글 검색

urlopen으로 읽어온 스트링에서 한글 검색하는 코드이다.

# -*- 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 wsgirefmodule 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=Truewhen the handler raises an exception, which prints debugging information to the web browser.

출처


2009년 11월 24일 화요일

앱 엔진 시작하기 start App Engine

앱 앤진 사용자 가입하기
http://code.google.com/intl/ko-KR/appengine/
(내 application ID : wogud86)

Google App Engine SDK for Python 다운받기
(필요하면 Download the Google App Engine Documentation도 다운)
http://code.google.com/intl/ko/appengine/downloads.html

D:\AppEngine\HelloWorld에 app.yaml파일 쓰기


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
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()

그리고 http://localhost:8080/창 새로 고침!!

이번엔 html을 분리시켜 보자.
같은 폴더안에 main.html 파일을 생성하고


Hello World



main.py를 수정한다.



#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://localhost:8080/창 새로 고침!!

작업이 끝났으면 다음과 같은 명령으로 웹에 올린다.

그리고 자신의 앱 계정에서 올라간 것을 확인할 수 있다.

샘플 코드 많은 곳 : http://code.google.com/p/google-app-engine-samples/
구현할 것 : http://me2box.com/63

구글 앱 엔진 소개 영상 Google App Engine

Introducing Google App Engine (pt. 1)




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')

2009년 11월 8일 일요일

블로그를 영어 학습 작업실로 바꿈니다.

구글 블로그를 처음쓰다보니 실수는 하는 군요..
다른 블로그는 카테고리 별로 나눌 수 있어서 이것도 그렇게 하려고 했는데.. -_-
다르다는 것을 깨닫고 카테고리별로 블로그를 생성합니다.
우선 영어 단어 학습기를 만들 생각으로 하는 프로젝트는 모두 이 블로그에 올리려 합니다.

2009년 10월 13일 화요일

라쿤의 작업실을 시작합니다.

그동안 사용해왔던 싸이월드를 접고 블로그를 시작합니다.

일상적인 내용은 네이버 블로그에,
작업과 관련된 내용은 이 블로그에 올려놓을 예정입니다.
싸이에 다 올려놓았던 것은 아쉽네요..

아직 사용법을 몰라 잘 할 수 있을지 걱정입니다.
모자라지만 지켜봐 주세요 ^^