I719 Fundamentals of Python/lecture4
From ICO wiki
Exceptions
this is a good overview:
https://docs.python.org/3/tutorial/errors.html
Slices
TASK 1
print out bitcoin price in console for EUR.
Example output
1064.4876
install requests
pip3 install requests
use requests
import requests
# make an HTTP GET request, and assign 'r' to response object
r = requests.get(my_url)
# convert response to python types, if response is JSON, and assign to 'data'
data = r.json()
my_dict = {'bpi': []}
# access value for key 'bpi'
my_dict['bpi']
print(my_dict['bpi'])
MAKE A WEBSITE
- Django
- Flask
- Bottle
- Falcon
pip3 install django python3 -m django startproject first_website cd first_website/first_website touch views.py cd ../ # go back to the original first website dir python3 manage.py runserver
Add a view
first_website/first_website/view.py
from django.http import HttpResponse
def my_view(request):
return HttpResponse('hi')
Add the view to the urls
first_website/first_website/view.py
from first_website.views import my_view
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('$', my_view)
]
Running an interactive shell with django
python3 manage.py shell
get a nicer shell
pip3 install ipython
Query string
the query string is converted to a dictionary like object available as the property GET
of the request
object
Task 2
Make a page that gives the bitcoin price in euros
Solution
import requests
from django.http import HttpResponse
def my_view(request):
# NOTE: requests with an 's' is the library
r = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
data = r.json()
price = data['bpi']['EUR']['rate']
response = HttpResponse(price)
return response