python from zero to hero (twitter explorer)

34
Python From Zero To Hero TwitterExplorer by Y. Senko and K. Leschenko

Upload: yuriy-senko

Post on 18-Jul-2015

408 views

Category:

Technology


5 download

TRANSCRIPT

Page 1: Python from zero to hero (Twitter Explorer)

Python From Zero To HeroTwitterExplorer

by Y. Senko and K. Leschenko

Page 2: Python from zero to hero (Twitter Explorer)

Before we start

Page 3: Python from zero to hero (Twitter Explorer)

Before we start

Add to your Vagrantfile:

config.vm.network "forwarded_port", guest: 5000, host: 5000

$ - run command in shell

mysql> - run command in MySQL console

In [12]: - execute in iPython interpreter

Page 4: Python from zero to hero (Twitter Explorer)

STEP 0: Create new virtual environment

$ cd /vagrant

$ virtualenv from_zero_to_hero

$ cd from_zero_to_hero

$ source bin/activate

Page 5: Python from zero to hero (Twitter Explorer)

STEP 0: Clone Git Repository

$ mkdir src

$ cd src

$ git clone https://github.com/ysenko/python-from-zero-to-hero.git

$ cd python-from-zero-to-hero/

$ git checkout step_0

Page 6: Python from zero to hero (Twitter Explorer)

Step 0: Project Structure

├── LICENSE├── README.md├── requirements.txt

└── twitter_explorer├── handlers

│ └── __init__.py├── __init__.py

└── twitter_backend└── __init__.py

requirements.txt - contains a list of

all PYTHON dependencies

handlers

twitter_backend

Page 7: Python from zero to hero (Twitter Explorer)

STEP 0: Install dependencies

$ pip install -r requirements.txt

Page 8: Python from zero to hero (Twitter Explorer)

STEP 1: "Hello World" application

$ git checkout step_1

Page 9: Python from zero to hero (Twitter Explorer)

STEP 2: Configuration

$ git checkout step_2

$ vim config/config.py

load_config() in application.py

$ echo "DEBUG = True" > ~/.twitter_explorer_conf.py

$ export TWITTER_EXPLORER_CONF=~/.twitter_explorer_conf.py

Page 10: Python from zero to hero (Twitter Explorer)

STEP 3: Unittests

$ git checkout step_3

$ nosetests tests

New directory tests

Base test class

Test for /

test_config.py

new load_config()

Page 11: Python from zero to hero (Twitter Explorer)

STEP 4: Templates

$ git checkout step_4

$ nosetests tests

http://127.0.0.1:5000

static/bootstrap

templates/base.html

Jinja2 http://flask.pocoo.org/docs/0.10/templating/

utils.render_template()

url_for() http://flask.pocoo.org/docs/0.10/api/#flask.url_for

Page 12: Python from zero to hero (Twitter Explorer)

STEP 5: DB and ORM

$ git checkout step_5

$ pip install -U -r requirements.txt

Page 13: Python from zero to hero (Twitter Explorer)

STEP 5: requirements.txt$ git diff step_4 step_5 -- requirements.txtdiff --git a/requirements.txt b/requirements.txtindex 2150589..4851485 100644--- a/requirements.txt+++ b/requirements.txt@@ -1,16 +1,21 @@Flask==0.10.1+Flask-Bcrypt==0.6.0+Flask-SQLAlchemy==1.0Jinja2==2.7.2MarkupSafe==0.23+PyMySQL==0.6.2PyYAML==3.11+SQLAlchemy==0.9.4Werkzeug==0.9.4argparse==1.2.1itsdangerous==0.24nltk==2.0.4+py-bcrypt==0.4tweepy==2.3.0wsgiref==0.1.2

# This is for tests and debug.-ipdb==0.8-ipython==2.1.0+ipdb+ipythonnose

Page 14: Python from zero to hero (Twitter Explorer)

STEP 5: requirements.txt

ipython: interactive Python console with awesome autocomplete (http://ipython.org/)

ipdb: interactive debugger based on ipython (https://pypi.python.org/pypi/ipdb)

SQLAlchemy: ORM (http://www.sqlalchemy.org/)

PyMySQL: Python MySQL client library (https://github.com/PyMySQL/PyMySQL)

py-bcrypt: password-hashing library for Python (http://www.mindrot.org/projects/py-bcrypt/)

Flask-Bcrypt, Flask-SQLAlchemy: Flask plugins, to make your life easier.

Page 15: Python from zero to hero (Twitter Explorer)

STEP 5: MySQL configuration Connect

$ mysql -uroot # add «-p» if you set password for MySQL root user during installation

Add databases:

mysql> create database twitter_explorer;mysql> create database twitter_explorer_test;

Add new users:

mysql> CREATE USER 'twitter_explorer'@'localhost' IDENTIFIED BY '123456';

Grant Privileges:

mysql> GRANT ALL PRIVILEGES on twitter_explorer.* to 'twitter_explorer'@'localhost'; mysql> GRANT ALL PRIVILEGES on twitter_explorer_test.* to 'twitter_explorer'@'localhost';

Page 16: Python from zero to hero (Twitter Explorer)

STEP 5: Tests again

Run$ nosetests tests

twitter_explorer/config

twitter_explorer/models.py(): create(), drop(), User model,

twitter_explorer/errors.py

tests/__init__.py: setup_package(), teardown_package()

tests/test_models.py

application.py: plugins initialization

twitter_explorer/__init__.py

Page 17: Python from zero to hero (Twitter Explorer)

`

$ ipython

In [1]: from twitter_explorer import models

In [2]: models.create()

In [4]: help(models.User.register) # You can read doc directly from python console

In [5]: user = models.User.register('root', 'root@root', 'qwerty123')

In [7]: user.emailOut[7]: u'root@root'

In [8]: user.usernameOut[8]: u'root'

In [9]: user.passwordOut[9]: u'$2a$12$HD8j/PCASgMehQSo4y4oqetpVZB509fB92hOi3o3TRv/7j0XmuRjK'

In [10]: user.check_password('123')Out[10]: False

In [11]: user.check_password('qwerty123')Out[11]: True

mysql> select * from user;

Page 18: Python from zero to hero (Twitter Explorer)

STEP 6: Add functionality … finally

$ git checkout step_6

$ pip install -U -r requirements.txt

$ nosetests tests

18

Page 19: Python from zero to hero (Twitter Explorer)

STEP 6: What’s new in requirements.txt

+Flask-WTF - forms validation, CSRF protection and other goods

https://flask-wtf.readthedocs.org/en/latest/

+Flask-Login - simple user session management for Flask

https://flask-login.readthedocs.org/en/latest/

19

Page 20: Python from zero to hero (Twitter Explorer)

STEP 6: New endpoints

$ vim twitter_explorer/__init__.py

+app.add_url_rule('/login', 'login', login.login, methods=['GET', 'POST'])

+app.add_url_rule('/signup', 'signup', login.register, methods=['GET', 'POST'])

+app.add_url_rule('/logout', 'logout', login.logout, methods=['GET'])

+app.add_url_rule('/', 'index', index.index, methods=['GET'])

20

Page 21: Python from zero to hero (Twitter Explorer)

STEP 6: login and logout

$ vim twitter_explorer/handlers/login.py

login()

logout()

register()

@login_required

LoginForm

SignUpForm

21

Page 22: Python from zero to hero (Twitter Explorer)

STEP 6: New templates

$ vim twitter_explorer/templates/base.html

$ vim twitter_explorer/templates/register.html

$ vim twitter_explorer/templates/login.html

22

Page 23: Python from zero to hero (Twitter Explorer)

STEP 6: Final review

$ git diff step_5 step_6

python twitter_explorer/__init__.py

Try to register a new user and login

23

Page 24: Python from zero to hero (Twitter Explorer)

STEP 7:Twitter backend $ git checkout step_7

$ nosetests tests

...

24

Page 25: Python from zero to hero (Twitter Explorer)

STEP 7: Keep calm and install dependencies

$ pip install -U -r requirements.txt

$ nosetests tests

25

Page 26: Python from zero to hero (Twitter Explorer)

STEP 7: Flask-Scripts$ vim manage.py

$ ./manage.py --help

$ ./manage.py db create

26

Page 27: Python from zero to hero (Twitter Explorer)

STEP 7: Twitter Auth $ vim twitter_explorer/twitter_backend/auth.py

Read more here https://dev.twitter.com/oauth

$ vim twitter_explorer/models.py

TwitterConfig

get_by_user()

update()

27

Page 28: Python from zero to hero (Twitter Explorer)

STEP 7: Register New Twitter APPhttps://apps.twitter.com/

28

Page 29: Python from zero to hero (Twitter Explorer)

STEP 7: Consumer Token and Secret

29

Page 30: Python from zero to hero (Twitter Explorer)

STEP 7: New config vars $ export TWITTER_EXPLORER_CONF=~/.twitter_explorer_conf.py

$ vim ~/.twitter_explorer_conf.py

Copy-paste TWITTER_TOKEN_KEY and TWITTER_TOKEN_SECRET into your local

config file.

30

Page 31: Python from zero to hero (Twitter Explorer)

STEP 7: Generate access token$ ipython

In [3]: from twitter_explorer.twitter_backend.auth import get_access_token

In [4]: consumer_token = 'tzrxWniFbssXf3n3lInGxgsPZ'In [5]: consumer_secret = '1iZBdRCqFmc9lcGTIcQITlz13gHE76LKSmPoOnj8as4ahRVAxf'

In [6]: get_access_token(consumer_token, consumer_secret)

Please open this URL in browser and grant access. Then copy verification code and paste it here.https://api.twitter.com/oauth/authorize?oauth_token=qFqbgHYTwukiAhQIWlj3XRMqqMmaoZuE

Verification code: 5029727

Access token key: 140718674-Rbd19jQ6xyM7g8mjFLeiupmN3nne92hVcvz6vOBzAccess token secret: rNApBcPFp8pfTh5vmTKGVRbu5xignY7sD9zAaFCfGNHSI

31

Page 32: Python from zero to hero (Twitter Explorer)

STEP 7: Set access credentials$ ipython

In [1]: from twitter_explorer.models import create

In [2]: create()

$ python twitter_explorer/__init__.py

Copy-paste access key and token into your account

32

Page 33: Python from zero to hero (Twitter Explorer)

STEP 7: Profit!!!

33

Page 34: Python from zero to hero (Twitter Explorer)

Q&A

The End!

34