Python

Lambda

https://medium.com/better-programming/how-to-use-lambda-expressions-in-python-a96330b513d4

Lambda Example - 模擬 switch

在Python中缺少其它語言中的switch陳述句,以下結合字典物件與lambda模擬switch的示範

score = int(input('請輸入分數:'))
level = score // 10
{
    10 : lambda: print('Perfect'),
    9  : lambda: print('A'),
    8  : lambda: print('B'),
    7  : lambda: print('C'),
    6  : lambda: print('D')
}.get(level, lambda: print('E'))()

在上例中,字典物件中的值的部份是lambda所建立的函式物件,你使用get()方法指定鍵,如果有符合的鍵,就傳回對應的函式物件並執行,否則就傳回get()第二個引數所指定的函式並執行,這模擬了switch中default的陳述。

List (Slicing)

https://railsware.com/blog/python-for-machine-learning-indexing-and-slicing-for-lists-tuples-strings-and-other-sequential-types/

Import

Python的import陷阱

https://pyliaorachel.github.io/blog/tech/python/2017/09/15/pythons-import-trap.html

Flask

Get parameter

from flask import Flask, request
app = Flask(__name__)

@app.route('/')
def hello_world():
	paramStr = request.args.get('paramStr',type = str) 
	return paramStr

Input:

http://127.0.0.1:5000/?paramStr=test123中文

Output:

test123中文

Allow Cross-origin AJAX

Handling Cross Origin Resource Sharing (CORS), making cross-origin AJAX

pip install -U flask-cors

Simple Usage

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
  return "Hello, cross-origin-world!"

https://flask-cors.readthedocs.io/en/latest/

Flask-Session

Managing Session Data in Flask with Flask-Session & Redis

https://hackingandslacking.com/managing-flask-session-variables-f4c5ccef54c0

run with https

https://stackoverflow.com/questions/28579142/attributeerror-context-object-has-no-attribute-wrap-socket/28590266#28590266

if __name__ == "__main__":
    context = ('cert.crt', 'key.key')
    app.run(host='0.0.0.0', port=80, ssl_context=context, threaded=True, debug=True)
if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8080, ssl_context=('/etc/letsencrypt/live/mdminhazulhaque.io/fullchain.pem', '/etc/letsencrypt/live/mdminhazulhaque.io/privkey.pem'))

validate https cert

https://bits.mdminhazulhaque.io/python/run-flask-app-with-let's-encrypt-ssl-certificate.html

openssl s_client -quiet -connect mdminhazulhaque.io:8080
openssl s_client -quiet -connect emsd-voicebot-webhook.abapi.info:80

I got errno=0 which means Flask is working fine with SSL. :D

PEP8 standards - Style Guide

Logging

Good logging practice

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

logger.info('Start reading database')
# read database here
records = {'john': 55, 'tom': 66}
logger.debug('Records: %s', records)
logger.info('Updating records ...')
# update records here
logger.info('Finish updating records')

Output:

INFO:__main__:Start reading database
INFO:__main__:Updating records ...
INFO:__main__:Finish updating records

change the logger level to DEBUG and see the output again

logging.basicConfig(level=logging.DEBUG)

Output:

INFO:__main__:Start reading database
DEBUG:__main__:Records: {'john': 55, 'tom': 66}
INFO:__main__:Updating records ...
INFO:__main__:Finish updating records

logging 教學

Numpy

Tips

Pandas

Tips

Tips

Determine if variable is defined

'a' in vars() or 'a' in globals()

if you want to be pedantic, you can check the builtins too 'a' in vars(__builtins__)

Code Example

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

people = [
    {'name': "Tom", 'age': 10},
    {'name': "Mark", 'age': 5},
    {'name': "Pam", 'age': 7}
]

def searchListDict(dataList, key='name', value=None):
    '''
    Searching a list of Dictionaries
    2018-05-16

    Param:  List of Dictionaries
    Return: Dictionary
    '''
    try:
        for l in dataList:
            if l[key] == value:
                return l

        logger.info('No Matching')
        return None # return None if finised looping & no matching

    except:
        logger.error('ERROR:', exc_info=True)

person = searchListDict(people, key='name', value='Pamx')
print(person)

min(None, x)

min(filter(lambda x: x is not None, lst)) if any(lst) else None
In [3]: lst = [None, 1, None]

In [4]: min(filter(lambda x: x is not None, lst)) if any(lst) else None
Out[4]: 1

In [5]: lst = [-4, None, 11]

In [6]: min(filter(lambda x: x is not None, lst)) if any(lst) else None
Out[6]: -4

In [7]: lst = [0, 7, -79]

In [8]: min(filter(lambda x: x is not None, lst)) if any(lst) else None
Out[8]: -79

In [9]: lst = [None, None, None]

In [10]: min(filter(lambda x: x is not None, lst)) if any(lst) else None

In [11]: print(min(filter(lambda x: x is not None, lst)) if any(lst) else None)
None

https://stackoverflow.com/questions/6254871/python-minnone-x

import numpy as np

lst = [1, 2, 3, 4, 5, None]

x = np.array(lst, dtype=np.float64)
print(x)
# array([  1.,   2.,   3.,   4.,   5.,  nan])

https://stackoverflow.com/questions/46025724/getting-max-value-from-a-list-with-none-elements

Get Max Value in Dict

def keywithmaxval(d):
     """ a) create a list of the dict's keys and values; 
         b) return the key with the max value"""  
     v=list(d.values())
     k=list(d.keys())
     return k[v.index(max(v))]

https://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary

Tools

Visual Studio Code

https://code.visualstudio.com/

Top 10 Visual Studio Code extensions for Python development

https://boostlog.io/@kazup01/top-10-visual-studio-code-extensions-for-python-development-5a8fdc46a7e5b7008ae1db2f

8 VS Code Extensions You Might Love

https://medium.com/better-programming/8-vs-code-extensions-you-might-love-eba03d85fd4f

Setting Sync

https://marketplace.visualstudio.com/items?itemName=Shan.code-settings-sync

Kite

https://kite.com

Automated RESTful API testing

Tavern

https://taverntesting.github.io/examples

Protect code

Troubleshoot

Mac OS X: ValueError: unknown locale: UTF-8

add these lines to your ~/.bash_profile

~/.bash_profile
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

ERROR: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is

FutureWarning: Conversion of the second argument of issubdtype from float to np.floating is deprecated. In future, it will be treated as np.float64 == np.dtype(float).type. from ._conv import register_converters as _register_converters

Problem: h5py issue (2.7.1

Solution: upgrade h5py (2.9.0)

pip install --upgrade h5py

17個新手常見的Python運行時錯誤

https://www.oschina.net/question/89964_62779

ERROR: ImportError: cannot import name 'Flask'

Problem: error while import 'flask'

>>> from flask import Flask
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/ryan/Python/github/flask/flask.py", line 9, in <module>
    from flask import Flask, jsonify, request, session
ImportError: cannot import name 'Flask'

Solution: The reason is your python file name is 'flask' in same directory.

Python的中文編碼處理

Library

Python library 集合

https://www.zhihu.com/question/24590883

https://kknews.cc/zh-hk/other/rb2m5m4.html

Reference:

Deploying a Machine Learning Model as a REST API

https://towardsdatascience.com/deploying-a-machine-learning-model-as-a-rest-api-4a03b865c166

Flask設置返回json格式數據

Multi-processing

Web Scrapping

https://micawber.readthedocs.io/en/latest/

Html2text - Convert HTML to Markdown-formatted text

http://alir3z4.github.io/html2text/

https://github.com/Alir3z4/html2text/blob/master/docs/usage.md

Audio Steaming

https://gist.github.com/hosackm/289814198f43976aff9b

Last updated