What is used to install and manage python packages globally?
pip: "pip installs packages". Like npm --global in javascript
What is an isolated working environment called in python?
virtualenv
If you want to run different versions of python in different projects, what would you use?
virtualenv: Creates an isolated working environment; enables side-by-side projects to work on different versions of python
What tool(s) in python are like a combination of nvm and node_modules in javascript?
pipenv: ties together pip and virtualenv to seem almost like npm and nvm working together.
What does PIPENV_VENV_IN_PROJECT=1 do?
It prevents pipenv from installing its virtual environments in a global area. Usually found in your shell init files like .bashrc, or .zshrc
What is the python version of package.json in javascript?
pipfile
Does pip understand pipfiles?
No! Only pipenv reads pipfiles.
How do you get a virtual environment setup in your project?
python versions
pipenv install --python "PYENV_ROOT/versions/3.8.1/bin/python"
OR pipenv install --python <version>
When you install the virtualenvironment in your project, what files do you get?
Now that you've installed virtualenv in your project, how do you activate it?
pipenv shell
: You will notice you have a prompt prepended your your normal prompt, showing your project directory in parens
What tool would you use to write python tests?
pytest : pipenv install pytest
How do you uninstall a package from your pipenv?
pipenv uninstall <packageName>
How would you install a version of pytest that is less than or equal to version 5.3?
pipenv install "pytest<=5.3"
How would you run something in your virtualenv without running the pipenv shell
?
pipenv run <programName>
How do you run unit tests in Python?
pipinstall pytest
python -m unittest
What module do you need to run unittests?
import unittest
What must your testcase class inherit from to use unittest?
unittest.TestCase
In your test folder, what additional file do you need in order to run your testcases?
__init__.py
What three parts must a unittest have in order to run?
Arrange, Act, and Assert
Where do you put your variable assignments and instance instantiations?
#Arrange area of your unittest function: s = Stack()
Where do you "do something" in your unit test function?
#Act: s.push()
Where do you evaluate your tests results in your unittest function?
#Assert: self.assertEqual(s.peek(), True)
where s.peek() is a function that returns a boolean
How do you name your unittest functions?
Name them what they are testing for: "test_peek_returns_last_item_but_does_not_remove_it_from_stack"
Write a unittest to pop the last item from the stack and remove it from the stack
import unittest
def TestStack(unittest.TestCase):
def test_constructor_is_no_arg(self):
#Arrange
s = Stack()
s.push(6.28)
#Act
result = s.pop()
#Assert
self.assertEqual(result, 6.28)
How do you create an environment to run pytest?
pipenv install --python 3.8.6
pipenv shell
pipenv install --dev pytest
__init__.py
file to your test folderpipenv install --dev pycodestyle
then in VSCode choose linter of pycodestylepytest
: to run pytestHow do you name test files in pytest?
If they begin with test, or end with test, then pytest understands it's a test file
Write a test to test that your class peek function returns the item on the stack, but does not pull it off the stack, using the Stack class.
from stack import Stack #import your class you're testing
def test_peek_returns_last_item_pushed_but_leaves_it_on_stack():
s = Stack()
s.push(6.28)
assert s.peek() == 6.28
assert len(s) == 1
How do you name your test cases in pytest?
make sure they all begin with the word test. They can be camel cased - but must begin with the word "test"
Does pytest understand unittest code?
Yes!
import unittest
from stack import Stack
class TestStack(unittest.TestCase):
def test_constructor_is_no_arg(self):
#Arrange
#Act
Stack()
#Assert
def test_new_stack_has_zero_elements(self):
#Arrange
s = stack()
#Act
result = len(s)
#Assert
self.assertEqual(result,0)
How do you skip a single test in pytest?
use the @pytest.mark.skip()
decorator above the function (or in unittest, the class). Note: You must import pytest to use the decorator.
Can you skip in the middle of a function in pytest?
Yes!
def test_new_stack_has_zero_elements():
if True:
pytest.skiip()
asert len(Stack()) == 0
What is a decorator
A function that takes in another function to extend its behavior and return a modified version of the inner function
Define metaprogramming
Dynamic modification through the use of Python decorators is a simple example of metaprogramming. Metaprogramming is when an object is created by other objects. Decorators are functions that return other functions.
Define introspection
The ability to examine objects to determine its behavior or type.
How would you "observe" an object?
use the dir() function: print(dir(myFunction))
# ['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
Write a decorator function that will return: "Hi, Julia, This is a message from Ryan." You will use kwargs and the function as follows:
@message_decorator
def say_hi(name):
return f'Hi, {name}'
print(say_hi(name='Julia', author='Ryan'))
def message_decorator(message_func):
def message_wrapper(*args, **kwargs):
message = message_func(kwargs['name'])
author = kwargs['author']
return f'{message}! This is a message from {author}.'
return message_wrapper
Give a couple examples of context managers
f = open('some_file.txt')
How would you manage a file using a try/catch block in python?
f = none
try:
f = open('some_file.txt')
# do some stuff
finally:
if f:
f.close()
Change the open code, using with
with open('some_file.txt') as f:
#do stuff with f like read the file
Use with to create a database connection and create a table called CREATE_USERS_TABLE_SQL using with
with psycopg2.connect(CONNECTION_PARAMETERS) as conn: with con.cursor() as curs: curs.execute(CREATE_USERS_TABLE_SQL)
What are the two key dunder methods used with with?
Create a class to be used with with that will print 2. In __enter__" and "4. In __exit"
class WithLogger:
def __enter__(self):
print("2. In __enter__")
return self
def __exit__(self, type, value, traceback):
print("4. In __exit__", type, value
return True
Now use the class you just created with a with statement:
print("1. Before with")
with WithLogger() as logger:
print("3. In with block")
print("5. After with")
This will print:
How do you install psycopg2?
pipenv install psycopg2-binary
HJow would you setup connection parameters for use with psycopg2?
CONNECTION_PARAMETERS = {
'dbname': 'psycopg_test_db',
'user': 'psycopg_test_user',
'password': 'password',
}
What are the steps for opening a psycopg2 connection, and closing it, without using with
import psycopg2
CONNECTION_PARAMETERS = {
'dbname': 'psycopg_test_db',
'user': 'psycopg_test_user',
'password': 'password',
}
#Connect to the database
conn = psycopg2.connect(**CONNECTION_PARAMETERS)
#Create a cursor
curs = conn.cursor()
#Do stuff ...
#Commit the changes to the database
conn.commit()
#Close the connection
curs.close()
conn.close()
How would you open a psycopg2 connection, create a cursor, execute some code, and close the connection with a with statement?
import psycopg2
CONNECTION_PARAMETERS = {
'dbname': 'psycopg_test_db',
'user': 'psycopg_test_user',
'password': 'password',
}
def change_car_owner(car_id, new_owner_id):
with psycopg2.connect(**CONNECTION_PARAMETERS) as conn:
with conn.cursor() as curs:
curs.execute("""
UPDATE cars SET owner_id = %(new_owner_id)s
WHERE id = %(car_id)s
"""
{'car_id': car_id,
'new_owner_id': new_owner_id})
change_car_owner(5, 1)
What are the datatype conversions between PostgreSQL and Python?
PostgreSQL | Pyton |
---|---|
NULL | None |
bool | bool |
double | float |
integer | long |
varchar | str |
text | unicode |
date | date |
How do you setup flask?
pipenv install Flask~=1.1
pipenv install python-dotenv~=0.13
#to use the .flaskenv fileHow do you check the flask version?
pipenv run flask --version
How would you create a route file using Flask?
from flask import Flask
app = Flask(__name__)
@app.route('/', methods=["GET", "POST"])
def hello():
return '
Hello, world!
'
What do you put in your .flaskenv file?
In your .flaskenv file, create the following entries:
FLASK_APP=<fileName>
FLASK_ENV=development
How do you run flask outside of the pipenv shell?
pipenv run flask run
In your route, how do you create a url that takes a path, and a variable, like "id"?
@app.route('/item/<id>') def item(id): return f'
How do you setup a route that serves two different routes with the same function?
@app.route('/')
@app.route('/home')
def home():
return '
Home
'
How would you perform some function BEFORE processing the request?
Use cases: opening a database connection or loading the logged-in user from the session.
@app.before_request
def before_request_function():
print("before_request is running")
How would you perform some function AFTER processing the request?
The function must take in the response as an argument, and must return a new, or the same response.
@app.after_request
def after_request_function(response):
print("after_request is running")
return response
How would you run a one-time initializer?
Runs before the first request is handled:
@app.before_first_request
def before_first_function():
print("before_first_request happens once"
How do you install Jinja?
pipenv install Jinja2~=2.11
, then make sure all your .html files are inside a templates folder
What do you need to import to display a Jinja template?
from flask import render_template
In your Jinja template, how would you write an if statement?
{% if not logged_in %}
<a href="/login">Log in</a>
{% endif %}
How do you write a for loop in a Jinja template?
<ul>
{% for item in navigation %}
<li>
<a href="{{ item.href }}">{{ item.caption }}</a>
</li>
{% endfor %}
</ul>
How doo you create a template, like a copyright in Jinja and include it in your templates?
In copyright.html:
© 2023 Me, myself, and I. All rights reserved.
In nav.html:
<a href="/">Home</a>
|
<a href="/about">About</a>
Then in your index.html file:
<html>
<head>
<title>{{ page }} = {{ sitename }} </title>
<head>
<body>
<h1>{{ sitename }}</h1>
<h2>{{ page }}</h2>
{% include 'nav.html' %}
<p>Coming soon to a browser near you...</p>
{% include 'copyright.html' %}
</body>
</html>
What does WT Forms use to prevent Cross-Site Request Forgery?
A SECRET_KEY
Where do you put your secret key?
Because it is supposed to be secret, you should put it in your .env file
How do you import your environment variables?
Use config.py:
import os
class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY') or 'default-key-for-devs'
Where do you use your config class?
You need to use it in your route file:
from flask import (Flask, render_template)
from app.config import Config
app = Flask(__name__)
app.config.from_object(Config) #populate Flask config dictionary from config class
What do you need to install to use Flask, Jinja, and WT Forms?
pipenv install Flask~=1.1
pipenv install Jinja2~=2.11
pipenv install python-dotenv~=0.13
pipenv install Flask-WTF~=0.14
What files need to be setup to use WT Forms?
How do you create your form.py file?
from flask_wtf import FlaskForm
from wtforms import StringField, SelectField, BooleanField, SubmitField
from wtforms.validators import DataRequired
class SampleForm(FlaskForm):
name = StringField('Name')
QUESTION
ANSWER
QUESTION
ANSWER
QUESTION
ANSWER
QUESTION
ANSWER
QUESTION
ANSWER
QUESTION
ANSWER
QUESTION
ANSWER
QUESTION
ANSWER
QUESTION
ANSWER
QUESTION
ANSWER
QUESTION
ANSWER
QUESTION
ANSWER
QUESTION
ANSWER
QUESTION
ANSWER
QUESTION
ANSWER
QUESTION
ANSWER
QUESTION
ANSWER
QUESTION
ANSWER
QUESTION
ANSWER
QUESTION
ANSWER