Tuesday 31 March 2020

Alembic. ModuleNotFoundError in env.py

When you run the alembic command, your app package is not in Python's module path. So it can't be imported. The easiest way to solve this is to use an extension such as Flask-Migrate or Flask-Alembic to handle setting up the migration environment for you. Both these extensions require you to use Flask-SQLAlchemy as well.
If you don't want to use an extension, the quick and dirty way is to just force the directory containing your app package to be on the path. In env.py, before importing Base, add
import os, sys
sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(__file__), '..')))
A better solution would be to properly set up your project with a setup.py file and install your package in editable mode: pip install -e .. Then your package would be on the path the "right" way, as if it were actually installed.

from : https://stackoverflow.com/questions/30427654/why-is-alembic-not-autogenerating

Alembic

Alembic is a lightweight database migration tool for usage with the SQLAlchemy Database Toolkit for Python.

from : https://alembic.sqlalchemy.org/en/latest/index.html

Wednesday 18 March 2020

Python 版本管理的好工具 - pyenv

Python 近 10 年來一直在演進,因此 Python 專案的開發也需要考慮版本的問題。
例如 Python 2 已經退休了,而現在的 Python 專案都以 Python 3 為主,然而有些公司內部的老舊專案仍以 Python 2 開發,因此開發者必須在 Python 2 與 3 之間進行切換。
如果你有 Python 版本切換上的困擾,那麼 pyenv 會是你的好朋友!

本文環境

  • macOS 10.15
  • zsh 5.7.1
安裝方式十分簡單,透過 homebrew 即可:
1
$ brew install pyenv

pyenv 設定

安裝 pyenv 完成之後,請執行以下指令,以進行後續的設定:
1
$ pyenv init
執行成功之後,會出現以下的提示,告訴我們必須在 ~/.zshrc 中加入 1 行 eval "$(pyenv init -)"
1
2
3
4
# Load pyenv automatically by appending
# the following to ~/.zshrc:

eval "$(pyenv init -)"
上述設定是登入系統後就自動啟用 pyenv 。
p.s. 如果是習慣使用 bash 的使用者,需修改 .bash_profile 而不是 .zshrc
設定完成後,執行以下指令讓 SHELL 重新啟動,讓 pyenv 的設定生效:
1
$ exec "$SHELL"
以上就完成設定囉!

pyenv 使用方法

pyenv 是用來幫助我們方便切換 Python 版本的工具,因此我們可以利用以下指令列出現在我們有哪些版本的 Python 可以使用:
1
2
$ pyenv versions
*  system
由於我們尚未安裝其他版本的 Python, 因此上述指令的結果只有 system ,也就是系統預設版本,在 macOS 中的版本仍是 python 2.7, 顯然不是我們應該使用的版本。
那麼 pyenv 提供哪些版本可供安裝呢?可以用以下指令列出:
1
2
3
4
5
6
7
8
$ pyenv install --list
  ...
  3.6.9
  3.7.0
  3.7-dev
  3.7.1
  3.7.2
  ...
查到版本後,就能以下指令安裝較新的版本,例如 Python 3.7.0 :
1
$ pyenv install 3.7.0
成功之後,再執行一次 pyenv versions ,就會發現多了 3.7.0 :
1
2
3
$ penv versions
*  system
   3.7.0
然後進一步用以下指令將系統預設的 Python 版本切換為 3.7.0 :
1
$ pyenv global 3.7.0
可以用以下指令驗證是否已經切換為 python 3.7.0 :
1
2
$ python --version
Python 3.7.0
如果只是短暫想切換 Python 版本的話,可以使用 pyenv local <版本> 指令切換,該指令就只會影響當前 session 的 Python 版本,例如:
1
$ pyenv local 3.6.5
以上就是 pyenv 的使用方法,有興趣想進一步了解 pyenv 的話可以到 pyenv GitHub 了解。

References



from : https://myapollo.com.tw/zh-tw/pyenv/