6月, 2016の投稿を表示しています


リスト要素でテーブルに代えること テーブルは推奨されない。リスト要素を使ってテーブルを表現してみる。 di (description item) を除く ui (unorderd list), oi (orderd list), li (list item) を使う。

Why Tables Are Bad (For Layout)Ulとli要素でテーブル風の表組み(段組み)を作ってみる | ゆゆぶろぐ<DIV>タグと<P>タグHTML5におけるDIVタグの使い方を紹介します【HTML5 実践編】

Generator is pretty faster than list

Generator iterates just once. List stores values. You choose one by your own case.

>>> timeit.timeit('(i for i in range(1000))',number=10000)
>>> timeit.timeit('[i for i in range(1000)]',number=10000)
>>> timeit.timeit('(i for i in range(10000))',number=10000)
>>> timeit.timeit('[i for i in range(10000)]',number=10000)
>>> timeit.timeit('(i for i in range(100000))',number=10000)
>>> timeit.timeit('[i for i in range(100000)]',number=10000)

python - Generator Expressions vs. List Comprehension - Stack Overflow

6/30 株取引 +900

3675 クロスマーケティング 100株@386 買付
3656 KLab 100株@650 買付
3675 クロスマーケティング 100株@384 買付
3675 クロスマーケティング 100株@385 売付
3656 KLab 100株@671 買付
3656 KLab 200株@668 売付

3656 KLab +1,200円
3675 クロスマーケティング -300円

Total  +900円

Flask リクエスト後の処理 (after_request)


fromflaskimportgdefafter_this_request(func):ifnothasattr(g,'call_after_request'):g.call_after_request=[]g.call_after_request.append(func)returnfunc@app.after_requestdefper_request_callbacks(response):forfuncingetattr(g,'call_after_request',()):response=func(response)returnresponse をコピペしソースコードにベタ書きしておき、次のようにレスポンスを受け取って返せばよいらしい。
@app.route('/') def index():@after_this_requestdefdo_this_after_request(response): # Do something: returnresponse
definvalidate_username_cache():@after_this_requestdefdelete_username_cookie(response):response.delete_cookie('username')returnresponse のようにして使う。

Per-Request After-Request Callbacks | Flask (A Python Microframework)

6/29 株取引 +10,450

6074, ジェイエスエス, 100株@870円で買付
6314, 石井工作研究所, 100株@393円で売付 (+8,800円)
6074, ジェイエスエス, 100株@888円で100株売付 (+1,650円)

損益 +10,450円

保有銘柄: なし

6/28 株取引 +750


6314, 石井工作研究所, 305円, 100株,買付

9980, マルコ, 181円, 100株, 買付
9980, マルコ, 190円, 100株, 売付

6314, 石井工作研究所, 340円, 100株, 保有

9980, マルコ, +750円

Total +750円

generator in flask

Found a way to yield values in flask. I wanted to send a large data, so this is useful. Here is a basic example.

from flask import Response @app.route('/large.csv') @app.route('/test') def test(): def generate(): app.logger.info('request started') for i in range(5): time.sleep(1) yield str(i) app.logger.info('request finished') yield '' return Response(generate(), mimetype='text/plain')
To understand generator, yield and streaming, go over following materials

Bigliographypython - Need to execute a function after returning the response in Flask - Stack Overflowhttps://jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/Streaming Contents — Flask Documentation (0.11)Video Streaming with Flask - miguelgrinberg.com

Install Python34 and libraries on Amazon EC2

Access to EC2 Default username is ec2-user. Check your public-dns of your ec2 and login by ssh -i path/to/your/key.pem ec2-user@public-dns
If you are in Cygwin terminal and Windows, you have to do a little more at first because of Cygwin7s bug. Try chgrp Users key.pem
chmod 400 key.pem
Install Python3.4 You have python2 by default, but no python3. You will find Python34, which is easily installed sudo yum list | grep python3 install it sudo yum install python34
Virtual Environment I created myenv in /usr/bin virtualenv -p python3.4 /usr/bin/myenv check if it works by [ec2-usr@ip...]$ source /usr/bin/myenv/bin/activate then your terminal has (myenv) in the beggining of current path. See which versions your python command runs  [ec2-usr@ip...]$ python >>> import sys; sys.version  , which should run with python 34. Now exit python by >>> exit() You can come out of virtual environment by (myenv)[ec2-usr@ip...]$ deactivate , but for now keep staying in the environment f…

読書メーターに登録した読みたい本からISBNをPythonでスクレイピング (Scraping bookmeter.com with Python)


# main code def get_isbns(bookmeterID): """ bookmeterID: Access your bookmeter page. Check the URL. You will see bookmeter.com/u/. Let number be an argument. The function returns a list of ISBNs """ ISBN10s = [] page=1 while True: url = 'http://bookmeter.com/u/{id}/booklistpre&p={page}'.format(**{'id':bookmeterID, 'page':page}) nextISBN10s = getISBNfromURL(url) # print(page, nextISBN10s) if nextISBN10s: ISBN10s.extend(nextISBN10s) page+=1 time.sleep(1) else: break return ISBN10s def getISBNfromURL(url): """ used in get_isbns(bookmeterID) """ page = reque…

Run/Execute python file on Apache2 with local server, ubuntu14.04LTS

Summary  I tried to run my python3 scripts on my local server with apache2 and ubuntu14.04LTS. I had permission problems and addressed it.

My firefox shows

Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator at webmaster@localhost to inform them of the time this error occurred, and the actions you performed just before this error.
More information about this error may be available in the server error log.
Apache/2.4.7 (Ubuntu) Server at localhost Port 80 also, in log file (/var/log/apache2/error.log), it says "Permission denied".

[Sun Jun 05 14:33:58.930599 2016] [core:notice] [pid 18049] AH00094: Command line: '/usr/sbin/apache2'
[Sun Jun 05 14:34:02.586809 2016] [cgi:error] [pid 18052] [client] AH01215: (13)Permission denied: exec of '/var/www/html/cgi-bin/first.py' failed
[Sun Jun 05 14:34:02.588022 2016] [cgi:error] …

Amazon Product API ItemLookup example with python3

This function returns a request about products. load_aws_keys() is not written here.def get_amazon_xml(*asins): access_key, secret_key = load_aws_keys() verb = 'GET' endpoint = 'http://webservices.amazon.co.jp/onca/xml' # .co.jp in Japan / .com in US if access_key is None or secret_key is None: print('No access key is available.') sys.exit() asin = ','.join([str(i) for i in asins]) query_dict = {'AWSAccessKeyId':access_key, 'AssociateTag':'asterisk37n-22', 'IdType':'ASIN', 'ItemId':asin, 'Operation':'ItemLookup', 'ResponseGroup':'Images,ItemAttributes,Offers', 'Service':'AWSECommerceService', 'Timestamp':datetime.datetime.utcnow().isoformat(), 'Version':'2013-08-01&#…

get xml's elements with namespace from Amazon Product API with lxml and Python3

You have to add namespace before every prefix like below.

import xml.etree.ElementTree as ET root = ET.fromstring(xml) # prepare xml nspace = '{http://webservices.amazon.com/AWSECommerceService/2013-08-01}' for item in root.findall('.//'+nspace+'Items/'+nspace+'Item/'+nspace+'ItemAttributes/'+nspace+'Title'): print(item.text, item.attrib) # or simpler way for item in root.findall('.//ns:Items/ns:Item/ns:ItemAttributes/ns:Title', namespaces={'ns':'http://webservices.amazon.com/AWSECommerceService/2013-08-01'}): print(item.text, item.attrib)

Also, beware that findall() only finds direct children like parent.findall(children).
findall() returns a list, find() not.

XPath and XSLT with lxml