2009-09-01から1ヶ月間の記事一覧

配列の便利スライス

data = [ 'a', 1, 'b', 2, 'c', 3, 'd', 4 ] # 2つとばしで取得 get_str = data[::2] get_num = data[1::2] 上記 get_str と get_num を出力 # get_str ['a', 'b', 'c', 'd' ] # get_num [1, 2, 3, 4]

辞書型の要素内の辞書型の要素でソート

メモしておく data = { 'a' : { 'name' : 'anna', 'age' : 17 }, 'b' : { 'name' : 'beck', 'age' : 15 }, 'c' : { 'name' : 'cherry', 'age' : 20 }, 'd' : { 'name' : 'detteiu', 'age' : 31 } } # (1) age の昇順ソートしたい result = sorted(data.items…

セッションに入れる、セッションから出す

def index(request): # 入れる request.session['user_key'] = 'abcde' # 出す print request.session['user_key'] # 結果 # abcde

URLから実行するモジュールを判断して実行させたい

やりたかったことは2点。 django & python で動的にモジュールを呼び出す python で可変引数を受け付ける関数を実現 というわけで「http://localhost:8000/api/image/set/」で「img/views.py の set()」が、「http://localhost:8000/api/image/own/list/」で…

作成できないアプリケーション名

↓これでエラーが出た > python manage.py startapp userエラーメッセージはこれ↓ Error: 'user' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name.既に user ってモジュールあるもんね。…

先頭だけ大文字にしたい

text = 'abcde' result = (text[0]).upper() + text[1:] # print result # 結果 # Abcde (追記)こんなのあったのか 3.6.1 文字列メソッド しかし指定した位置の文字だけ大文字または小文字にして返すなんてメソッドは無いのか… そういうのが必要な時点で何か…

GAEの画像処理リソース使って画像のサムネイル生成&データストアへ保存

ここを参考にした。 Images Python API - Google App Engine - Google Code 画像をアップロード 元画像と生成したサムネイル画像を保存 保存した画像を表示する これらを実現できた。やったね! アプリケーション作成 > python manage.py startapp img manag…

リダイレクト(HttpResponseRedirect)

http://localhost/ で実行していたとして。これは http://www.google.com/ にリダイレクトされる。 # -*- coding: utf-8 -*- from django.http import HttpResponseRedirect def index(request): return HttpResponseRedirect("http://www.google.com/") こ…

トラックバック

トラックバックって言及する時に使うものなのか。関連情報とかその程度の認識だった…あちゃー

データストアにあるデータから、Noneのものを取得またはNone以外を取得、そして昇順降順でソートする

こんなクラス(Store)があったとして・・・ models.py # -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ from google.appengine.ext import db class Store(db.Model): name = db.StringProperty() phone = db.StringProper…

Pythonで画像処理がしたいので、PIL(Python Image Library)モジュールを使う…ためのインストールメモ

python版GAE用SDK(windows)を使うとき、PILモジュールが無いよというエラーが出ていたので、解決しました。 エラー詳細 > python manage.py runserver WARNING:root:Could not initialize images API; you are likely missing the Python "PIL" module. Impo…

CSVファイルをアップロードしてデータストアへ格納

アップロードするcsvファイルの文字コードはsjisとした場合。models.py # -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ from google.appengine.ext import db class Import(db.Model): # データ作成日時 created_date = …

Google App Engine のデータストアには全文検索に対応した何かが無いので Python にがんばってもらった

くそがmodels.py # -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ from google.appengine.ext import db class Message(db.Model): created_date = db.DateTimeProperty(auto_now_add = True) fulltext = db.TextProperty…

画像をデータストアへ保存&データストアの画像を画面へ出力

urls.py とかは随時適切に記述models.py # -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ from google.appengine.ext import db class Image(db.Model): # 画像を登録した日時 created_date = db.DateTimeProperty(auto_n…

PATH_INFO を使ってメソッドを指定して実行(改修後)

http://hogehoge.com/dinamic/aaaaa というURLでアクセスした際に、aaaaa() というメソッドを実行させたい!という場合urls.py # -*- coding: utf-8 -*- from django.conf.urls.defaults import * urlpatterns = patterns( 'dinamic.views' ,(r'^$', 'index'…

会社宛の電話での話し方

自社にかかってきた電話に出て相手に対して「ちょっといま○○は席を外してるんでー戻り次第折り返すように伝えますんでー」って語尾を延ばす話し方をしてるの聞いて「お前何様?」とか思ったのは今朝だけでいい

CSV出力

とりあえず写経していじった。写経元はこちら。 Django で CSV を出力する - Django v1.0 documentation」 # -*- coding: utf-8 -*- from django.http import HttpResponse import csv def getcsv(request): response = HttpResponse(mimetype='text/csv') r…

PATH_INFO を使ってメソッドを指定して実行

http://hogehoge.com/dinamic/aaaaa というURLでアクセスした際に、aaaaa() というメソッドを実行させたい!という場合urls.py # -*- coding: utf-8 -*- from django.conf.urls.defaults import * urlpatterns = patterns( 'dinamic.views' ,(r'^$', 'index'…

定義済の名前を dir() で取得できる

名前空間がどうのこうのという時に便利。リスト型で取得される。 print dir() #['_', # '__builtins__', # '__doc__', # '__file__', # '__name__' #] import os print dir() #['_', # '__builtins__', # '__doc__', # '__file__', # '__name__', # 'os' #] …

os.environ

import os print type(os.environ) # <type 'instance'> print os.environ #{'HTTP_COOKIE': 'sessionid=********************************', # 'SERVER_SOFTWARE': 'Development/1.0', # 'SCRIPT_NAME': '', # 'REQUEST_METHOD': 'GET', # 'HTTP_KEEP_ALIVE': '300', # 'SERV</type>…

データモデルで StringPropertyに 入力値の制限をつける(choicesを使う)

国名を格納する箇所に、指定された国名以外を保存したくない場合、等。こんな定義の時に class Human(db.Model): country = db.StringProperty(u'コンテンツ', required = True) こうすればいいらしい class Human(db.Model): country = db.StringProperty(u…

正規表現:変数の中には数字しか入ってない事を確認したい

正規表現を英語にすると「Regular Expression」ということで、reモジュールなるものがあった。 これを使う。 import re if re.match('^[0-9]{1,}$', text): return True else: return False これでもいいらしい import re if re.match('^\d{1,}$', text): re…

プログラムファイルとテンプレートファイルの位置関係

開発してると、プログラムファイルとテンプレートファイルは別々になってる。プログラマーはプログラムファイルをいじる。デザイナー(マークアッパー)はテンプレートファイルをいじる。で、以下の2パターンがあるとする。(1) root/ + appl/ + programA + …

PHPのinclude()に相当することをPythonでやりたい

つまり別ファイルに記載されている関数を使いたい PHP find.php function findHuman(country) { // 処理する return result; } main.php include('./find.php'); $result = findHuman('japan'); こんな感じの事をPythonでやりたいの Python find.py def find…

変数の型を調べたい

こうなんだね。 isinstance(data, int) # int # float # str # list # tuple # dict # file (追記)ただし、Noneだけはこうだった。 data == None

テンプレートディレクトリの設定はどうすればいいの?

すでに http://[host]/sample/top/ で sample/views.py の top() モジュールが呼ばれるようになっている、とする。あとテンプレートディレクトリ(になる予定)の中に top.html ファイルが設置されている、とする。で、やりたいことは top() モジュールが te…

静的ファイルはどうすればいいの?

(例) templates/html/display.html に置いたファイルに http://[host]/html/display.html でアクセスしたい 方法 1.アプリケーションディレクトリにある app.yaml ファイルを開く 2.handlers に設定を追記 # アドレスで使用する文字列 - url: /html # 静的フ…

手持ちのCentOS5.2にPython2.5.2をいれた

# python -V Python 2.4.3 気に入らなかったので2.5.2をソースから入れた # cd /usr/local/src # wget http://www.python.org/ftp/python/2.5.2/Python-2.5.2.tgz # tar zxvf Python-2.5.2.tgz # cd Python-2.5.2 # ./configure --prefix=/usr/local/Python2…

Python(GAE:appengine patch)うにょうにょ型と文字コード編

rec_data = u"ああああ" rec_data = rec_data.encode('UTF-8') print type(rec_data) print rec_data pre_data = request.GET['firstname'] pre_data = pre_data.encode('UTF-8') print type(pre_data) print pre_data うん、エラーは出ないんだけどね。なん…

Pythonの型がうにゃうにゃうー

1. PHPで書くとこうなるコードを if ( is_null($data) === true ) { return 'Data is null'; } else { return $data; } Pythonで書きたい。 if $data is None: return 'Data is null' else: return $data これでいいのかな 2. PHPで書くとこうなるコードを $…