Drkcore

16 06 2010 Python Tweet

web.pyで画像アップローダーを

しゃべるにtwitpicみたいなものが欲しくなったので、昼休みに画像アップローダーを書いてみた。

文字列のランダム化はodz bufferを参考にして、ロゴはtwitlogoを使った。

アーカイブはここ

shovelpic

web.pyはstaticっていうディレクトリのファイルは静的なものとして扱ってくれるのと環境変数はweb.ctxでアクセスできる。

#!/usr/bin/env python
# -*- encoding:utf-8 -*-

# kzfm <kerolinq@gmail.com>
import web
import string
from random import randrange

alphabets = string.digits + string.letters

def randstr(n=4):
    return ''.join(alphabets[randrange(len(alphabets))] for i in xrange(n))

image_dir = "images"

urls = (
    '/', 'Index',
    '/(.*)', 'Show',

        )

html_template = """<html><header><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</header><body>
<img src="/static/shovelpic.png" /><br />
%s
</body></html>"""

class Index:
    def GET(self):
        form = """<form method="POST" enctype="multipart/form-data" action="">
<input type="file" name="myfile" />
<input type="submit" />
</form>"""
        return html_template % form

    def POST(self):
        mol = web.input(myfile={})
        if mol['myfile'].filename == "":
           raise web.seeother('/')
        else:
            h = web.ctx.homedomain
            imgid = randstr()
            imgurl  = "%s/%s.png" % (image_dir,imgid)
            imgfile  = "static/%s/%s.png" % (image_dir,imgid)
            f = open(imgfile,"w")
            f.write(mol['myfile'].value)
            f.close()
            snip = "Your imageurl is <a href=\"%s/%s\">%s/%s</a>" % (h,imgid,h,imgid)
            return html_template % snip

class Show:
    def GET(self,imagename):
        img = "/" + image_dir + "/" + imagename + ".png"
        imgurl = "<img src=\"/static%s\" width=500 />" % img

        return html_template % imgurl

if __name__ == "__main__":
   app = web.application(urls, globals())
   app.run()

web.pyはちょっとしたものを書くときには便利だ。

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021