uniquejava / blog

My notes regarding the vibrating frontend :boom and the plain old java :rofl.
Creative Commons Zero v1.0 Universal
11 stars 5 forks source link

python 2020 #293

Open uniquejava opened 4 years ago

uniquejava commented 4 years ago

see also https://github.com/uniquejava/blog/issues/62

pyenv

pyenv相当于node.js中的n或nvm, 用来全局切换python的版本(在pyenv作用范围内)

virtualenv类似于不带 -g 参数的npm,基于当前python解释器给项目创建一个隔离的python环境。

show me the code!

# 安装pyenv
$ brew install pyenv 

# 安装python 3.7.3
$ pyenv install 3.7.3

# 设置373为pyenv的默认python版本
$ pyenv global 3.7.3

# 查看pyenv当前的python版本
$ pyenv version
3.7.3 (set by /Users/cyper/.pyenv/version)

# 打开terminal时立即激活pyenv
$ echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n  eval "$(pyenv init -)"\nfi' >> ~/.zshrc

# I start by resetting the shell
$ exec $SHELL 
$ which python
/Users/cyper/.pyenv/shims/python
$ python -V
Python 3.7.3
$ pip -V
pip 19.0.3 from

详见: https://gtbensmagazine.com/2019/05/07/the-right-and-wrong-way-to-set-python-3-as-default-on-macos/

virtualenv

注意: 只有在项目根目录下创建venv, vs code才能自动检测到

pip install virtualenv
cd my_project
python -m venv venv
. venv/bin/activate

如果不是在项目根目录下。 可以自行修改.vscode/settings.json文件

{
  "python.pythonPath": "${workspaceFolder}/venv/bin/python3",
  "python.formatting.provider": "yapf"
}

pip (不要用pip freeze命令!手工维护requirements.txt)

pip install flask python-dotenv

# 其他
pip list
pip freeze > requirements.txt
pip install -r requirements.txt

hello flask

api.py

import time
from flask import Flask

app = Flask(__name__)

@app.route('/time')
def get_current_time():
  return {'time': time.time()}

最新的flask (1.1.0+) 已经不需要jsonify了。👏

.flaskenv

FLASK_APP=api.py
FLASK_ENV=development
➜ flask run                
 * Serving Flask app "api.py" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 191-109-957

gitignore

venv
__pycache__

详见: https://blog.miguelgrinberg.com/post/how-to-create-a-react--flask-project

uniquejava commented 4 years ago

Scrapy Tutorial

https://docs.scrapy.org/en/latest/intro/tutorial.html

Klein Tutorial

官方文档: https://klein.readthedocs.io/en/latest/introduction/1-gettingstarted.html#this-introduction

为什么要用? Going asynchronous: from Flask to Twisted Klein

Simplest Flask

from flask import Flask, jsonify, request, render_template

app = Flask(__name__)

stores = [{
    'name': 'My Wonderful Store',
    'items': [{
        'name': 'My Item',
        'price': 15.99
    }]
}]

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/stores', methods=['POST'])
def create_store():
    data = request.get_json()
    new_store = {'name': data['name'], 'items': []}
    stores.append(new_store)
    return jsonify(new_store)

@app.route('/stores/<string:name>')
def get_store(name):
    for store in stores:
        if store['name'] == name:
            return jsonify(store)

    return jsonify({'message': 'store not found.'})

@app.route('/stores')
def get_stores():
    return jsonify({'stores': stores})

@app.route('/stores/<string:name>/items', methods=['POST'])
def create_item_in_store(name):
    data = request.get_json()
    for store in stores:
        if store['name'] == name:
            new_item = {'name': data['name'], 'price': data['price']}
            store['items'].append(new_item)
            return jsonify(new_item)

    return jsonify({'message': 'store not found'})

@app.route('/stores/<string:name>/items')
def get_items_in_store(name):
    for store in stores:
        if store['name'] == name:
            return jsonify(store['items'])

    return jsonify({'message': 'no items found in this store.'})

app.run(port=5000, debug=True)