Python development & problems

venv setup, activate & exit

  1. setup:
    1
    $ python3 -m venv
  2. activate:
    1
    2
    $ . venv/Scripts/activate        # windows
    $ source venv/bin/activate # linux & Mac OS
  3. exit:
    1
    $ deactivate
    ref: https://blog.csdn.net/weixin_30292745/article/details/101445788?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~aggregatepage~first_rank_v2~rank_aggregation-3-101445788.pc_agg_rank_aggregation&utm_term=python+%E5%85%B3%E9%97%ADvenv&spm=1000.2123.3001.4430

setup flask development env inside react project

take my project as an example:

  1. mkdir react-app/api/
  2. under api/, create file named api.py
  3. (venv) pip install python-dotenv
  4. create .env file under /api
  5. write the following content into .env:
    1
    2
    FLASK_APP=api.py
    FLASK_ENV=development
    start server:
    1
    $ flask run
    ref: https://stackoverflow.com/questions/54600434/how-to-set-flask-env-inside-config-file

UnicodeEncodeError

  1. ‘charmap’ codec can’t encode characters in position 87-93: character maps to
    https://stackoverflow.com/questions/27092833/unicodeencodeerror-charmap-codec-cant-encode-characters
    tried multiple ways to print the raw context directly but failed, but it can be written into files with
    1
    2
    with open('books.txt', 'a', encoding='utf-8') as f:
    f.write(json.dumps(item, ensure_ascii=False) + '\n')

    UnicodeEncodeError: ‘charmap’ codec can’t encode character ‘\u0130’

    ‘\u0130’ is ‘I’ in Latin, charmap is the default encoding format used locally.
    solution: <target-string>.encode('utf-8')
    Note, it cannot be fully handled with above encoding function, it actually turn out to be like "\u0130stanbul"
    currently I have no better solution but add one more function to translate the Latin letter to English …

pip install & version control under vitural env

  1. check how many modules are installed in current env:
    1
    $ pip list
  2. check where pip installed package is:
    1
    $ pip show <module-name>
    e.g.
    1
    2
    3
    4
    5
    6
    7
    8
    $ pip show phantomjs
    Name: phantomjs
    Version: 1.4.1
    Summary: Python wrapper for PhantomJS
    Location: c:\users\...\appdata\local\programs\python\python37-32\lib\site-packages
    Requires:
    Required-by:
    (venv)
  3. generating requirements.txt for all required packages:
    1
    $ pip freeze > requirements.txt
  4. pip install all required packages in requirements.txt:
    1
    $ pip install -r requirements.txt