id
int64
0
25.6k
text
stringlengths
0
4.59k
400
web browser you should see response like this"resources""core""limit" "remaining" "reset" }"search""limit" "remaining" "reset" }"rate""limit" "remaining" "reset" the information we're interested in is the rate limit for the search api we see at that the limit is requests per minute and that we have requests remaining f...
401
url ' requests get(urlprint("status code:" status_codestore api response in variable response_dict json(print("total repositories:"response_dict['total_count']explore information about the repositories repo_dicts response_dict['items' namesstars [][for repo_dict in repo_dictsv names append(repo_dict['name']stars append...
402
refining pygal charts let' refine the styling of our chart we'll be making few different customizationsso first restructure the code slightly by creating configuration object that contains all of our customizations to pass to bar()python_ repos py --snip-make visualization my_style ls('# 'base_style=lcsu my_config pyga...
403
minor labels in this chart are the project names along the -axis and most of the numbers along the -axis the major labels are just the labels on the -axis that mark off increments of stars these labels will be largerwhich is why we differentiate between the two at we use truncate_label to shorten the longer project nam...
404
chart x_labels ['httpie''django''flask' plot_dicts {'value' 'label''description of httpie '}{'value' 'label''description of django '}{'value' 'label''description of flask '} chart add(''plot_dictschart render_to_file('bar_descriptions svg'at we define list called plot_dicts that contains three dictionariesone for the h...
405
python_ repos py --snip-explore information about the repositories repo_dicts response_dict['items'print("number of items:"len(repo_dicts) namesplot_dicts [][for repo_dict in repo_dictsnames append(repo_dict['name'] plot_dict 'value'repo_dict['stargazers_count']'label'repo_dict['description']plot_dicts append(plot_dict...
406
pygal also allows you to use each bar in the chart as link to website to add this capabilitywe just add one line to our codeleveraging the dictionary we've set up for each project we add new key-value pair to each project' plot_dict using the key 'xlink'python_ repos py --snip-namesplot_dicts [][for repo_dict in repo_d...
407
'id' 'kids'[ the dictionary contains number of keys we can work withsuch as 'urlu and 'titlev the key 'descendantscontains the number of comments an article has received the key 'kidsprovides the ids of all comments made directly in response to this submission each of these comments may have kids of their own as wellso...
408
ids to build set of dictionaries that each store information about one of the current submissions we set up an empty list called submission_dicts at to store these dictionaries we then loop through the ids of the top submissions we make new api call for each submission by generating url that includes the current value ...
409
discussion linkcomments titleour nexus devices are about to explode discussion linkcomments --snip-you would use similar process to access and analyze information with any api with this datayou could make visualization showing which submissions have inspired the most active recent discussions try it yourse lf - other l...
410
app ic
411
ge ting ta te ith dja ngo behind the scenestoday' websites are actually rich applications that act like fully developed desktop applications python has great set of tools for building web applications in this you'll learn how to use django (learning log--an online journal system that lets you keep track of information ...
412
and we'll refine the learning log project and then deploy it to live server so you (and your friendscan use it setting up project when beginning projectyou first need to describe the project in specificationor spec then you'll set up virtual environment to build the project in writing spec full spec details the project...
413
if you're using an earlier version of python or if your system isn' set up to use the venv module correctlyyou can install the virtualenv package to install virtualenventer the followingpip install --user virtualenv keep in mind that you might need to use slightly different version of this command (if you haven' used p...
414
running in installing django once you've created your virtual environment and activated itinstall django(ll_env)learning_logpip install django installing collected packagesdjango successfully installed django cleaning up (ll_env)learning_logbecause we're working in virtual environmentthis command is the same on all sys...
415
browser requests the wsgi py file helps django serve the files it creates the filename is an acronym for web server gateway interface creating the database because django stores most of the information related to project in databasewe need to create database that django can work with to create the database for the lear...
416
it reports the version of django in use and the name of the settings file being usedand at it reports the url where the project is being served the url requests on port on your computer--called localhost the term localhost refers to server that only processes requests on your systemit doesn' allow anyone else to see th...
417
django project is organized as group of individual apps that work together to make the project work as whole for nowwe'll create just one app to do most of the work for our project we'll add another app to manage user accounts in you should still be running runserver in the terminal window you opened earlier open new t...
418
def __str__(self)"""return string representation of the model ""return self text we've created class called topicwhich inherits from model-- parent class included in django that defines the basic functionality of model only two attributes are in the topic classtext and date_added the text attribute is charfield-- piece...
419
the project add our app to this tuple by modifying installed_apps so it looks like this--snip-installed_apps --snip-'django contrib staticfiles'my apps 'learning_logs'--snip-grouping apps together in project helps to keep track of them as the project grows to include more apps here we start section caled my appswhich i...
420
when you define models for an appdjango makes it easy for you to work with your models through the admin site site' administrators use the admin sitenot site' general users in this sectionwe'll set up the admin site and use it to add some topics through the topic model setting up superuser django allows you to create u...
421
admin py in the same directory as models pyadmin py from django contrib import admin register your models here to register topic with the admin siteenterfrom django contrib import admin from learning_logs models import topic admin site register(topicthis code imports the model we want to registertopic uand then uses ad...
422
the topics admin pageand you'll see the topic you just created let' create second topic so we'll have more data to work with click add againand create second topicrock climbing when you click saveyou'll be sent back to the main topics page againand you'll see both chess and rock climbing listed defining the entry model...
423
the __str__(method tells django which information to show when it refers to individual entries because an entry can be long body of textwe tell django to show just the first characters of text we also add an ellipsis to clarify that we're not always displaying the entire entry migrating the entry model because we've ad...
424
when to follow these guidelines and when to disregard these suggestions when you click saveyou'll be brought back to the main admin page for entries here you'll see the benefit of using text[: as the string representation for each entryit' much easier to work with multiple entries in the admin interface if you see only...
425
print(topic idtopic chess rock climbing we store the queryset in topicsand then print each topic' id attribute and the string representation of each topic we can see that chess has an id of and rock climbing has an id of if you know the id of particular objectyou can get that object and examine any attribute the object...
426
- short entriesthe __str__(method in the entry model currently appends an ellipsis to every instance of entry when django shows it in the admin site or the shell add an if statement to the __str__(method that adds an ellipsis only if the entry is more than characters long use the admin site to add an entry that' fewer ...
427
users request pages by entering urls into browser and clicking linksso we'll need to decide what urls are needed in our project the home page url is firstit' the base url people use to access the project at the momentthe base urlsite that lets us know the project was set up correctly we'll change this by mapping the ba...
428
at the beginning of the file we then import the url functionwhich is needed when mapping urls to views we also import the views module wthe dot tells python to import views from the same directory as the current urls py module the variable urlpatterns in this module is list of individual pages that can be requested fro...
429
response based on the data provided by views the following code is how the view for the home page should be writtenfrom django shortcuts import render def index(request)"""the home page for learning log""return render(request'learning_logs/index html'when url request matches the pattern we just defineddjango will look ...
430
although it may seem complicated process for creating one pagethis separation between urlsviewsand templates actually works well it allows you to think about each aspect of project separatelyand in larger projects it allows individuals to focus on the areas in which they're strongest for examplea database specialist ca...
431
focus on developing the unique aspects of each page and makes it much easier to change the overall look and feel of the project the parent template we'll start by creating template called base html in the same directory as index html this file will contain elements common to all pagesevery other template will inherit f...
432
now we need to rewrite index html to inherit from base html here' index htmlindex html {extends "learning_logs/base html% {block content %learning log helps you keep track of your learningfor any topic you're learning about {endblock content %if you compare this to the original index htmlyou can see that we've replaced...
433
firstwe define the url for the topics page it' common to choose simple url fragment that reflects the kind of information presented on the page we'll use the word topicsso the url will return this page here' how we modify learning_logs/urls pyurls py """defines url patterns for learning_logs ""--snip-urlpatterns home p...
434
dictionary in which the keys are names we'll use in the template to access the data and the values are the data we need to send to the template in this casethere' one key-value pairwhich contains the set of topics we'll display on the page when building page that uses datawe pass the context variable to render(as well ...
435
each pass through the loop the braces won' appear on the pagethey just indicate to django that we're using template variable the html tag indicates list item anything between these tagsinside pair of tagswill appear as bulleted item in the list at we use the {empty %template tagwhich tells django what to do if there ar...
436
the url pattern for the topic page is little different than the other url patterns we've seen so far because it will use the topic' id attribute to indicate which topic was requested for exampleif the user wants to see the detail page for the topic chesswhere the id is the url will be localhost: /topics/ here' pattern ...
437
for specific information when you're writing queries like these in your own projectsit' very helpful to try them out in the django shell first you'll get much quicker feedback in the shell than you will by writing view and template and then checking the results in browser note the topic template the template needs to d...
438
before we look at the topic page in browserwe need to modify the topics template so each topic links to the appropriate page here' the change to topics htmltopics html --snip-{for topic in topics %{topic }{empty %--snip-we use the url template tag to generate the proper linkbased on the url pattern in learning_logs wit...
439
in this you started learning how to build web applications using the django framework you wrote brief project specinstalled django to virtual environmentlearned to set up projectand checked that the project was set up correctly you learned to set up an app and defined models to represent the data for your app you learn...
440
acc at the heart of web application is the ability for any useranywhere in the worldto register an account with your app and start using it in this you'll build forms so users can add their own topics and entriesand edit existing entries you'll also learn how django guards against common attacks to form-based pages so ...
441
before we build an authentication system for creating accountswe'll first add some pages that allow users to enter their own data we'll give users the ability to add new topicadd new entryand edit their previous entries currentlyonly superuser can enter data through the admin site we don' want users to interact with th...
442
the url for new page should be short and descriptiveso when the user wants to add new topicwe'll send them to here' the url pattern for the new_topic pagewhich we add to learning_logsurls pyurls py --snip-urlpatterns --snip-page for adding new topic url( '^new_topic/$'views new_topicname='new_topic')this url pattern wi...
443
the two main types of request you'll use when building web apps are get requests and post requests you use get requests for pages that only read data from the server you usually use post requests when the user needs to submit information through form we'll be specifying the post method for processing all of our forms (...
444
{csrf_token %{form as_p }add topic {endblock content %this template extends base htmlso it has the same base structure as the rest of the pages in learning log at we define an html form the action argument tells the server where to send the data submitted in the formin this casewe send it back to the view function new_...
445
adding new entries now that the user can add new topicthey'll want to add new entries too we'll again define urlwrite view function and templateand link to the page but first we'll add another class to forms py the entry modelform we need to create form associated with the entry modelbut this time with little more cust...
446
we need to include topic_id argument in the url for adding new entrybecause the entry must be associated with particular topic here' the urlwhich we add to learning_logs/urls pyurls py --snip-urlpatterns --snip-page for adding new entry url( '^new_entry/(? \ +)/$'views new_entryname='new_entry')this url pattern matches...
447
the definition of new_entry(has topic_id parameter to store the value it receives from the url we'll need the topic to render the page and process the form' dataso we use topic_id to get the correct topic object at at we check if the request method is post or get the if block executes if it' get requestand we create bl...
448
nextwe need to include link to the new_entry page from each topic pagetopic html {extends "learning_logs/base html%{block content %topic{topic }entriesadd new entry --snip-{endblock content %we add the link just before showing the entriesbecause adding new entry will be the most common action on this page figure - show...
449
the url for the page needs to pass the id of the entry to be edited here' learning_logs/urls pyurls py --snip-urlpatterns --snip-page for editing an entry url( '^edit_entry/(? \ +)/$'views edit_entryname='edit_entry')the id passed in the url (for exampleedit_entry/ /is stored in the parameter entry_id the url pattern s...
450
form prefilled with information from the existing entry object the user will see their existing data and be able to edit that data when processing post requestwe pass the instance=entry argument and the data=request post argument to tell django to create form instance based on the information associated with the existi...
451
displayed we use the {url %template tag to determine the url for the named url pattern edit_entryalong with the id attribute of the current entry in the loop (entry idthe link text "edit entryappears after each entry on the page figure - shows what the topic page looks like with these links figure - each entry now has ...
452
in this section we'll set up user registration and authorization system to allow people to register an account and log in and out we'll create new app to contain all the functionality related to working with users we'll also modify the topic model slightly so every topic belongs to certain user the users app we'll star...
453
urls that belong to the learning_logs app from urls that belong to the users app the login page we'll first implement login page we'll use the default login view django providesso the url pattern looks little different make new urls py file in the directory learning_log/users/and add the following to iturls py """defin...
454
{endblock content %this template extends base html to ensure that the login page will have the same look and feel as the rest of the site note that template in one app can extend template from another app if the form' errors attribute is setwe display an error message ureporting that the username and password combinati...
455
should see login page similar to the one shown in figure - enter the username and password you set up earlierand you should be brought back to the index page the header on the home page should display greeting personalized with your username figure - the login page logging out now we need to provide way for users to lo...
456
from django http import httpresponseredirect from django core urlresolvers import reverse from django contrib auth import logout def logout_view(request)"""log the user out "" logout(requestw return httpresponseredirect(reverse('learning_logs:index')we import the logout(function from django contrib auth in the function...
457
the following code provides the url pattern for the registration pageagain in users/urls pyurls py --snip-urlpatterns login page --snip-registration page url( '^register/$'views registername='register')this pattern matches the url sends requests to the register(function we're about to write the register(view function t...
458
authenticate(functions to log in the user if their registration information is correct we also import the default usercreationform in the register(functionwe check whether or not we're responding to post request if we're notwe make an instance of usercreationform with no initial data if we're responding to post request...
459
nextwe'll add the code to show the registration page link to any user who is not currently logged inbase html --snip-{if user is_authenticated %hello{user username }log out {else %register log in {endif %--snip-now users who are logged in see personalized greeting and logout link users not logged in see registration pa...
460
django makes it easy to restrict access to certain pages to logged-in users through the @login_required decorator decorator is directive placed just before function definition that python applies to the function before it runs to alter how the function code behaves let' look at an example restricting access to the topi...
461
django makes it easy to restrict access to pagesbut you have to decide which pages to protect it' better to think about which pages need to be unrestricted first and then restrict all the other pages in the project you can easily correct overrestricting accessand it' less dangerous than leaving sensitive pages unrestri...
462
the modification to models py is just two linesmodels py from django db import models from django contrib auth models import user class topic(models model)""" topic the user is learning about""text models charfield(max_length= date_added models datetimefield(auto_now_add=trueowner models foreignkey(userdef __str__(self...
463
now that we know the idswe can migrate the database (venv)learning_logpython manage py makemigrations learning_logs you are trying to add non-nullable field 'ownerto topic without defaultwe can' do that (the database needs something to populate existing rowsw please select fix provide one-off default now (will be set o...
464
chess ll_admin rock climbing ll_admin we import topic from learning_logs models and then loop through all existing topicsprinting each topic and the user it belongs to you can see that each topic now belongs to the user ll_admin note you can simply reset the database instead of migratingbut that will lose all existing ...
465
the entrieseven though you're logged in as different user we'll fix this now by performing check before retrieving the requested entries in the topic(view functionviews py from django shortcuts import render from django http import httpresponseredirecthttp from django core urlresolvers import reverse --snip-@login_requ...
466
initial requestpre-fill form with the current entry --snip-we retrieve the entry and the topic associated with this entry we then check if the owner of the topic matches the currently logged-in userif they don' matchwe raise an http exception associating new topics with the current user currentlyour page for adding new...
467
- refactoringthere are two places in views py where we make sure the user associated with topic matches the currently logged-in user put the code for this check in function called check_topic_owner()and call this function where appropriate - protecting new_entrya user can add new entry to another user' learning log by ...
468
app learning log is fully functional nowbut it has no styling and runs only on your local machine in this we'll style the project in simple but professional manner and then deploy it to live server so anyone in the world can make an account for the styling we'll use the bootstrap librarya collection of tools for stylin...
469
simple web applicationsmake them look goodand deploy them to live server you'll also be able to use more advanced learning resources as you develop your skills styling learning log we've purposely ignored styling until now to focus on learning log' functionality first this is good way to approach developmentbecause an ...
470
enables some of the interactive elements that the bootstrap template provides add this code to the end of settings pysettings py --snip-my settings login_url '/users/login/settings for django-bootstrap bootstrap 'include_jquery'truethis code spares us from having to download jquery and place it in the correct location ...
471
easier to understand modifying base html we need to modify the base html template to accommodate the bootstrap template 'll introduce the new base html in parts defining the html headers the first change to base html defines the html headers in the file so whenever learning log page is openthe browser title bar display...
472
<button type="buttonclass="navbar-toggle collapseddata-toggle="collapsedata-target="#navbararia-expanded="falsearia-controls="navbar"learning log topics {if user is_authenticated %hello{user username }log out {else %register log in {endif %the first element is the opening tag the body of an html file contains the conte...
473
directly from the previous version of base html at we place second list of navigation linksthis time using the selector navbar-right the navbar-right selector styles the set of links so it appears at the right edge of the navigation bar where you typically see login and registration links here we'll display the user gr...
474
let' update the home page using the newly defined header block and another bootstrap element called jumbotron-- large box that will stand out from the rest of the page and can contain anything you want it' typically used on home pages to hold brief description of the overall project while we're at itwe'll update the me...
475
{bootstrap_form form % {buttons %log in {endbuttons %{endblock content %at we load the bootstrap template tags into this template at we define the header blockwhich describes what the page is for notice that we've removed the {if form errors %block from the templatedjangobootstrap manages form errors automatically at w...
476
let' make the rest of the pages look consistent as well we'll update the new_topic page nextnew_topic html {extends "learning_logs/base html%{load bootstrap % {block header %add new topic{endblock header %{block content % <form action="{url 'learning_logs:new_topic%}method='postclass="form"{csrf_token %{bootstrap_form ...
477
{topic }{empty %no topics have been added yet {endfor % add new topic {endblock content %we don' need the {load bootstrap %tagbecause we're not using any custom bootstrap template tags in this file we add the heading topics inside the header block we style each topic as an element to make them little larger on the page...
478
there are no entries for this topic yet {endfor %{endblock content %we first place the topic in the header block we then delete the unordered list structure previously used in this template instead of making each entry list itemwe create panel div element at vwhich contains two more nested divsa panel-heading div and p...
479
- other formswe've applied bootstrap' styles to the login and add_topic pages make similar changes to the rest of the form-based pagesnew_entry and edit_entryand register - stylish bloguse bootstrap to style the blog project you created in deploying learning log now that we have professional-looking projectlet' deploy ...
480
package fails to install correctly the package dj-database-url helps django communicate with the database heroku usesdj-static and static help django manage static files correctlyand gunicorn is server capable of serving apps in live environment (static files contain style rules and javascript files note some of the re...
481
psycopg >if any of the packages didn' install on your systemadd those as well when you're finishedyour requirements txt file should include each of the packages shown above if package is listed on your system but the version number differs from what' shown herekeep the version you have on your system note if you're usi...
482
if os getcwd(='/app' import dj_database_url databases 'default'dj_database_url config(default='postgres://localhost' honor the ' -forwarded-protoheader for request is_secure(secure_proxy_ssl_header ('http_x_forwarded_proto''https' allow all host headers allowed_hosts ['*' static asset configuration base_dir os path dir...
483
we also need to modify wsgi py for herokubecause heroku needs slightly different setup than what we've been usingwsgi py --snip-import os from django core wsgi import get_wsgi_application from dj_static import cling os environ setdefault("django_settings_module""learning_log settings"application cling(get_wsgi_applicat...
484
heroku toolbelt will be installed the output shows that gunicorn has been started with process id of in this example at gunicorn is listening for requests on port in additiongunicorn has started worker process ( to help it serve requests visit should see the learning log home pagejust as it appears when you use the dja...
485
you make your first commit ignoring files we don' need git to track every file in the projectso we'll tell git to ignore some files make file called gitignore in the folder that contains manage py notice that this filename begins with dot and has no file extension here' what goes in gitignoregitignore ll_env__pycache__...
486
branch and that our working directory is clean this is the status you'll want to see any time you push your project to heroku pushing to heroku we're finally ready to push the project to heroku in an active terminal sessionissue the following commandsu (ll_env)learning_logheroku login enter your heroku credentials emai...
487
customize this error page shortly at we see that the process defined in procfile has been started now we can open the app in browser using the command heroku open(ll_env)learning_logheroku open opening afternoon-meadow- done this command spares you from opening browser and entering the url heroku showed youbut that' an...
488
in this section we'll refine the deployment by creating superuserjust as we did locally we'll also make the project more secure by changing the setting debug to falseso users won' see any extra information in error messages that they could use to attack the server creating superuser on heroku you've already seen that w...
489
you'll probably want your url to be friendlier and more memorable than single command(ll_env)learning_logheroku apps:rename learning-log renaming afternoon-meadow- to learning-log done git remote heroku updated (ll_env)learning_logyou can use lettersnumbersand dashes when naming your appand call it whatever you wantas ...
490
so the only server allowed to host the project is heroku you need to use the name of your appwhether it' the name heroku providedsuch as afternoon-meadow- herokuapp comor the name you chose at we set debug to falseso django won' share sensitive information when an error occurs committing and pushing changes now we need...
491
your project with an extension we haven' defined for exampletry to visit page on your live deployment that doesn' give away any specific information about the project if you try the same request on the local version of learning log at django error page the result is perfectyou'll see informative error messages when you...
492
--snip-}--snip-this change tells django to look in the root template directory for the error page templates viewing the error pages locally if you want to see what the error pages look like on your system before pushing them to herokuyou'll first need to set debug=false on your local settings to suppress the default dj...
493
ca master -master (ll_env)learning_logwe issue the git add command at because we created some new files in the projectso we need to tell git to start tracking these files then we commit the changes and push the updated project to heroku now when an error page appearsit should have the same styling as the rest of the si...
494
session with heroku run bash and run the command python manage py migrate then visit your live projectand make sure the changes you expect to see have taken effect it' easy to make mistakes during this processso don' be surprised when something goes wrong if the code doesn' workreview what you've done and try to spot t...
495
- live blogdeploy the blog project you've been working on to heroku make sure you set debug to false and change the allowed_hosts settingso your deployment is reasonably secure - more sthe get_object_or_ (function should also be used in the new_entry(and edit_entry(views make this changetest it by entering url like err...
496
congratulationsyou've learned the basics of python and applied your knowledge to meaningful projects you've made gamevisualized some dataand made web application from hereyou can go in number of different directions to continue developing your programming skills firstyou should continue to work on meaningful projects t...
497
if you write gamelet other people play it if you make visualizationshow it to others and see if it makes sense to them if you make web appdeploy it online and invite others to try it out listen to your users and try to incorporate their feedback into your projectsyou'll become better programmer if you do when you work ...
498
ins ta lling py thon python has several different versions and number of ways it can be set up on each operating system this appendix is useful if the approach in didn' workor if you want to install different version of python than the one that came with your system python on linux python is included by default on almo...
499
open terminal window and issue the following commandpython --version python the result shows that the default version is howeveryou might also have version of python installed to checkenter the following commandpython --version python python is also installed it' worth running both commands before you attempt to instal...