<Flask, Python> リクエストコンテキストで遊ぶ。
リクエストコンテキストrequest context
で遊ぶ。
つまり、リクエストを受けた状態、で遊ぶ。
その1
with
でrequest context
状態にする。
In [1]: from flask import request, Flask In [2]: app = Flask('aaa') In [3]: with app.test_request_context('/hello', method='POST'): ...: print(request.path) ...: /hello
その2
RequestContext
をプッシュpush
する。
こっちの方が遊びやすい。
In [9]: ctx = app.test_request_context('/hello', method='POST') In [10]: ctx.push() In [11]: request.url Out[11]: 'http://localhost/hello' In [12]: type(ctx) Out[12]: flask.ctx.RequestContext In [13]: dir(ctx) Out[13]: ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_after_request_functions', '_implicit_app_ctx_stack', '_preserved_exc', 'app', 'auto_pop', 'copy', 'flashes', 'g', 'match_request', 'pop', 'preserved', 'push', 'request', 'session', 'url_adapter'] In [14]: type(request) Out[14]: werkzeug.local.LocalProxy In [15]: dir(request) Out[15]: ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_get_file_stream', '_get_stream_for_parsing', '_is_old_module', '_load_form_data', '_parse_content_type', 'accept_charsets', 'accept_encodings', 'accept_languages', 'accept_mimetypes', 'access_route', 'application', 'args', 'authorization', 'base_url', 'blueprint', 'cache_control', 'charset', 'close', 'content_encoding', 'content_length', 'content_md5', 'content_type', 'cookies', 'data', 'date', 'dict_storage_class', 'disable_data_descriptor', 'encoding_errors', 'endpoint', 'environ', 'files', 'form', 'form_data_parser_class', 'from_values', 'full_path', 'get_data', 'get_json', 'headers', 'host', 'host_url', 'if_match', 'if_modified_since', 'if_none_match', 'if_range', 'if_unmodified_since', 'input_stream', 'is_multiprocess', 'is_multithread', 'is_run_once', 'is_secure', 'is_xhr', 'json', 'list_storage_class', 'make_form_data_parser', 'max_content_length', 'max_form_memory_size', 'max_forwards', 'method', 'mimetype', 'mimetype_params', 'module', 'on_json_loading_failed', 'parameter_storage_class', 'path', 'pragma', 'query_string', 'range', 'referrer', 'remote_addr', 'remote_user', 'routing_exception', 'scheme', 'script_root', 'shallow', 'stream', 'trusted_hosts', 'url', 'url_charset', 'url_root', 'url_rule', 'user_agent', 'values', 'view_args', 'want_form_data_parsed']
マニュアル。
http://flask.pocoo.org/docs/0.12/quickstart/#context-locals
http://flask.pocoo.org/docs/0.12/shell/#creating-a-request-context
<Python, gspread> 読み書き。
gspread
での読み書き。
まずは、コネクトして、Spreadsheet
オブジェクトを作る。
In [4]: import os In [6]: import json In [7]: import gspread In [8]: from oauth2client.service_account import ServiceAccountCredentials In [9]: scope = ['https://spreadsheets.google.com/feeds'] ...: doc_id = 'hogehogehoge' ...: path = os.path.expanduser('./hogehoge.json') ...: credentials = ServiceAccountCredentials.from_json_keyfile_name(path, scope) ...: client = gspread.authorize(credentials) ...: In [10]: gc = client.open_by_key(doc_id) In [11]: wb = gc.open('sheet1') AttributeErrorTraceback (most recent call last) <ipython-input-11-e8624d9591e8> in <module>() ----> 1 wb = gc.open('sheet1') AttributeError: 'Spreadsheet' object has no attribute 'open'
ふーん、、、
じゃってことで、dir()
でアトリビュートを調べる。
In [12]: dir(gc) Out[12]: ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_feed_entry', '_fetch_sheets', '_sheet_list', 'add_worksheet', 'client', 'del_worksheet', 'get_id_fields', 'get_worksheet', 'id', 'sheet1', 'title', 'worksheet', 'worksheets']
じゃ、worksheet()
でアクセスってことで、、
In [13]: sh = gc.worksheet('sheet1') In [14]: dir(sh) Out[14]: ['_MAGIC_NUMBER', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_cell_addr', '_cell_addr_re', '_create_update_feed', '_element', '_fetch_cells', '_finder', '_get_link', '_id', '_title', 'acell', 'add_cols', 'add_rows', 'append_row', 'cell', 'client', 'col_count', 'col_values', 'export', 'find', 'findall', 'get_addr_int', 'get_all_records', 'get_all_values', 'get_id_fields', 'get_int_addr', 'id', 'insert_row', 'range', 'resize', 'row_count', 'row_values', 'spreadsheet', 'title', 'update_acell', 'update_cell', 'update_cells', 'updated', 'version'] In [15]: sh.title Out[15]: 'sheet1'
なるへそ。
で、初期値確認。
In [26]: sh.get_all_values() Out[26]: [['1', 'a', 'b', 'c'], ['2', 'd', 'e', 'f'], ['3', 'g', 'h', 'i']]
いろいろアクセス。
In [27]: sh.range('A1:C1') Out[27]: [<Cell R1C1 '1'>, <Cell R1C2 'a'>, <Cell R1C3 'b'>] In [28]: sh.cell(1,1).value Out[28]: '1'
で、セル更新。
In [29]: sh.update_cell(4,1, 'hage') In [30]: sh.get_all_values() Out[30]: [['1', 'a', 'b', 'c'], ['2', 'd', 'e', 'f'], ['3', 'g', 'h', 'i'], ['hage', '', '', '']]
いけるねー。
<Python, requests> 郵便番号ゲット
Python
でもやってみた。
In [69]: import requests In [70]: r = requests.get('http://zipcloud.ibsnet.co.jp/api/search', params={'zipcode':'7830060'}) In [71]: requests.get('http://zipcloud.ibsnet.co.jp/api/search?callback', params={'zipcode':'7830060'}) Out[71]: <Response [200]> In [72]: r = requests.get('http://zipcloud.ibsnet.co.jp/api/search', params={'zipcode':'7830060'}) In [73]: r.content Out[73]: b'{\n\t"message": null,\n\t"results": [\n\t\t{\n\t\t\t"address1": "\xe9\xab\x98\xe7\x9f\xa5\xe7\x9c\x8c",\n\t\t\t"address2": "\xe5\x8d\x97\xe5\x9b\xbd\xe5\xb8\x82",\n\t\t\t"address3": "\xe8\x9b\x8d\xe3\x81\x8c\xe4\xb8\x98",\n\t\t\t"kana1": "\xef\xbd\xba\xef\xbd\xb3\xef\xbe\x81\xef\xbd\xb9\xef\xbe\x9d",\n\t\t\t"kana2": "\xef\xbe\x85\xef\xbe\x9d\xef\xbd\xba\xef\xbd\xb8\xef\xbd\xbc",\n\t\t\t"kana3": "\xef\xbe\x8e\xef\xbe\x80\xef\xbe\x99\xef\xbd\xb6\xef\xbe\x9e\xef\xbd\xb5\xef\xbd\xb6",\n\t\t\t"prefcode": "39",\n\t\t\t"zipcode": "7830060"\n\t\t}\n\t],\n\t"status": 200\n}' In [74]: import json In [75]: json.loads(r.content.decode()) Out[75]: {'message': None, 'results': [{'address1': '高知県', 'address2': '南国市', 'address3': '蛍が丘', 'kana1': 'コウチケン', 'kana2': 'ナンコクシ', 'kana3': 'ホタルガオカ', 'prefcode': '39', 'zipcode': '7830060'}], 'status': 200}
<jQuery> getJSON
jQuery
javascript
でjson
データを引っ張るには、、、
$.getJSON
だ。 だー、だー、だー、、、。
郵便番号zipcode
を引っ張るスクリプトscript
。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Zipcode</title> </head> <body> <form> <div> <label for="zip">Zipcode</label><br /> <input id="zip" type="text" size="10" /> <input id="search" type="button" value="Search" /> </div> <div> <label for="address">Address</label><br /> <input id="address" type="text" size="35" /> </div> </form> </body> <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <script> $(function() { $('#search').click(function() { $.getJSON('http://zipcloud.ibsnet.co.jp/api/search?callback=?', { zipcode: $('#zip').val() } ) .done(function(data) { if (data.results) { var result = data.results[0]; $('#address').val(result.address1 + result.address2 + result.address3); } else { $('#address').val('No address matched'); } }); }); }); </script> </html>
<Google Cloud Platform> _winreg
もう解決できないのかと思った、このエラー。
ImportError: No module named _winreg
解決できた。
/c/Users/Nekoyuki/AppData/Local/Google/Cloud SDK/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/sandbox.py
中の次のリストに、_winreg
を追加する。
_WHITE_LIST_C_MODULES = [ 'array', '_ast', 'binascii', : : '_winreg', # 追加! 'zipimport', 'zlib', ]
動いたよー。 ようやく。
長かった。。。
<conda, dos, Python> dos上でconda
dos
上で、conda
して、Python
環境を切り替える方法。
C:\>where activate C:\Anaconda3\Scripts\activate C:\Anaconda3\Scripts\activate.bat C:\>conda info -e # conda environments: # py27 * C:\Anaconda3\envs\py27 root C:\Anaconda3 C:\>activate py27 (py27) C:\>
いいねー。 いけるねー。