Giter Site home page Giter Site logo

book2-exercises's Introduction

Exercises for Real Python Part 2: Web Development with Python by Michael Herman. Share with the world!

book2-exercises's People

Contributors

asimonia avatar augustogoulart avatar mjhea0 avatar mroswell avatar ni8mr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

book2-exercises's Issues

Book 2 - Page 81

if x in set(["1", "2", "3", "4"]):

Can be simplified to:

if x in {"1", "2", "3", "4"}:

Obviously, the result is the same for both, but you can avoid the function call with the latter.

Book 2 - Page 116

On page 116 going into page 117, item #9 instructs us to "Refactor".

However, the code block that follows, even when copied and pasted, doesn't function properly. After a bit of debugging, I found that answer was bound to a string, so in the elif, we're trying to compare a string to an int resulting in a failure every time.

It is possible that this was intentional to get us to continue debugging and practicing to get it working; however, I very nearly moved on, since that fact was clearly stated.

PS - it is entirely possible that I did something else wrong and this entire issue is moot. :)

Book 2 - Page 181

Before the in line 40, there should be an opening

tag that corresponds to the closing tag on line 47.

Grammar error

Page 586 - Please, use comma instead period.

One of the main features of MongoEngine. Despite the fact that Mongo does not require a schema

Should be:
One of the main features of MongoEngine, despite the fact that Mongo does not require a schema

Book 2 - Page 189

NON - ISSUE - I guess I still haven't mastered the art of proper indentation.

The test.py script, as shown on this page, doesn't work, and the test_user_setup function doesn't exist in the book2-exercises master to compare.

Ninja edit: I'm seeing the same problem for the test.py that begins on page 191.

As a test, I copied the complete test.py script from flasktaskr-03 in the master, and it executed and ran the tests properly.

About AddTaskForm() class in forms.py at project folder of flasktaskr-02/book2-exercises

Hello, I am not able to understand the process of defining 'task_id' like this-

task_id = IntegerField('Priority')

My question is why we are using 'Priority' within IntegerField().

I have my own explanation that we are going to use that in 'priority' so that we can prioritize tasks using the task_id. But i am not sure here.

I couldn't find any 'help tag' here or else it would been 'help' issue. I am following your Real Python books part 2 now. I couldn't find any forums for such kind of questions either.

pymongo 3.0 vs 2.8

Going through chapter 29. on page 586 you're asked to create an app. When doing so, I get this error:

"mongoengine.connection.ConnectionError: Cannot connect to database default: False is not a read preference."

I used django 1.8.2 and pymongo 3.0.2.
Was able to fix it by using pymongo 2.8.

A typo at latest update - Page 303

Hello, at the page 303 of the book, the test of the response for the URL of invalid task_id is defined like this-

def test_invalid_resource_endpoint_returns_error(self):
            self.add_tasks()
            response = self.app.get('api/tasks/209', follow_redirects=True)
            self.assertEquals(response.status_code, 200)
            self.assertEquals(response.mimetype, 'application/json')
            self.assertIn('Element does not exist', response.data)

There is a typo in the line-

self.assertEquals(response.status_code, 200)

The returned status code should be 404, according to the defined route of project/views.py.

Image between text

Please review pages 613 and 614.
Figure 30.2: Django Flat Pages App - adding a new page. This is along the HTML code, and it's confusing the reader.

15.1.1.2 instructions

In 15.1.1.2 Write Code section it says:

“Simply add the above code to the else block in the login() function. ”

It should be

“Simply add the above code to the if block in the login() function. ”

RealPython Part 2, Page 312 Installing RVM

I was working through book two in the Travis CI Setup section, and I got to the point where I am supposed to installed RVM. I would recommend adding two steps in the OSX/Linux section

  1. Add key first: gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3. I couldn't install RVM without it!
  2. After installing the RVM, I had to restart my machine so I could run the rvm install 1.9.3 command. I read you could also use bash -l.

Thanks again for the great book! I am learning a ton!

</script> closing in wrong place

This is the wrong code:

<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript"></script>

{% block extrahead %}
{% endblock %}
</script>

Here is how it should be:

<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript"> {% block extrahead %} {% endblock %} </script>

Real Python Part 2/flasktaskr-01 404 error

Hello,
I'm struggling whit a 404 error after I login whit admin, admin into mine flasktaskr application.
It is not redirecting me to tasks.html and I am unable to see the template. I'm trying to google an answer but I'm very confused about this.
Have tried everything but it still give me 404 after I login.
This is the output http://127.0.0.1:5000/post?username=user&password=pass, how to debug this?

This is mine repository for the application https://github.com/Copser/AddFlaskTaskr.

Book 2, p. 117 [7.10 (Add posts)] - Routes Order Clarification

trying to add the 'add' route and function at the end of the 'blog.py' file results with error. Text should mention the right place, and the reason for it. (For me it worked when I placed the 'add's after the 'login' route and before the 'main' one).

Real Python Part 2: 14.3.2

Not sure why people are referring to page #'s...the page #'s change depending on your viewer, right?

Anyway...
14.3.2
3 says:
“Add “static” and “templates” directories within both the “tasks” and “users” directories.”

But right after that you list how the directory structure should look, and those folders aren't in tasks and users. Nor are they in the git solution.

Step 4 does not make a lot of sense, either. I'm guessing that steps 3 and 4 should be removed.

User registration should extend default user model not replace

In chapter 21, you guys use stripe to process user payments. This is done by replacing the default django user model for an custom user model, is this the best practice?

Even on the django documentation they kind of advise against it (look at the warning): https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#substituting-a-custom-user-model

I think the best practice would be to extend the user model with the necessary information your user needs and let the default user model handle the default fields like username, firstname, is_staff, email etc., am i wrong?

About 404 error handling in FlaskTaskr

Hello, in the book, the 404 error handling process is defined like this-

@app.errorhandler(404)
def internal_error(error):
    return render_template('404.html'), 404

Is it necessary to write a 404 after render_template('404.html')? The function has worked without it-

@app.errorhandler(404)
def internal_error(error):
    return render_template('404.html')

It is at 281 page of the book.

typing error

on page 595:

Instead of:
Ad the Database layer:
Should be:
At the Database layer:

Instead of:
Thinka bout testing as well:
Should be:
Think about testing as well:

Bugs in django_ecommerce Payments App?

  1. In my payments.views.register, my app crashes upon a post request because stripe_token is None. I understand it is using the hiddenInput widget, and therefore must get set from the server, but I do not see where this happens anywhere. For example if UserForm was a ModelForm, specifying a default value for stripe_token would fix this problem. How is this dealt with in your code?

  2. In templates/cardform.html, line 26 defines a label that seems to never be used.
    label for="expiry_date">Expiration date</label
    Did you mean for line 26 to be this?
    div class="input" id="expiry_date

Thank you!
Jonathan

Change to Heroku commands, Book 2 Page 285

When I try to execute

heroku addons:add heroku-postgresql:dev

I receive the following error:

WARNING: heroku addons:add has been deprecated. Please use heroku addons:create instead.
! That add-on plan is only available to select users.

I could still fire up my app, login, add, remove, and mark tasks as complete. I'm not sure how the Postgres db fits in, but mine still worked. Just wanted to make everyone aware!

errors in errors of register html

Each of the four fields contains this if statement:
{% if form.name.errors %}

should be:
{% if form.email.errors %}
{% if form.password.errors %}
{% if form.confirm.errors %}

AttributeError at /sign_in for the mvp

Hey everyone, does anyone else get an error while trying to log_in with a previous registered account?

AttributeError at /sign_in
'User' object has no attribute 'check_password'

traceback

Request Method: POST
Request URL: http://127.0.0.1:8000/sign_in
Django Version: 1.6.5
Exception Type: AttributeError
Exception Value:
'User' object has no attribute 'check_password'
Exception Location: /home/mat/Desktop/django-projects/book2-exercises/django_mvp/mvp/payments/views.py in sign_in, line 24
Python Version: 2.7.5

looks like its comming from the payments/views.py

if results[0].check_password(form.cleaned_data['password']):
def sign_in(request):
    user = None
    if request.method == 'POST':
        form = SigninForm(request.POST)
        if form.is_valid():
            results = User.objects.filter(email=form.cleaned_data['email'])
            if len(results) == 1:
                if results[0].check_password(form.cleaned_data['password']):
                    request.session['user'] = results[0].pk
                    return HttpResponseRedirect('/')
                else:
                    form.addError('Incorrect email address or password')
            else:
                form.addError('Incorrect email address or password')
    else:
        form = SigninForm()

    print form.non_field_errors()

    return render_to_response(
        'sign_in.html',
        {
            'form': form,
            'user': user
        },
        context_instance=RequestContext(request)
    )

Thanks for any headsup!

Book 2 - Page 113

On page 113 going into page 114, item #3 instructs us to "add pdb.set_trace() within the function to set your first breakpoint".

However, the code block that follows doesn't have it added, nor does it have the import pdb.

May be a missing 'validators'

At chapter 10, Page 159-160 of the Real Python Part-2 book, we are defining RegisterForm() class for allowing the new user to register.

There, we are adding 'confirming password' feature like this-

confirm = PasswordField(
    'Repeat Password',
    [DataRequired(), EqualTo('password', message='Passwords must match')]
    )

I think the terms within third braces should be assigned to 'validators' like this-

confirm = PasswordField(
    'Repeat Password',
    validators = [DataRequired(), EqualTo('password', message='Passwords must match')]
    )

If my assumption is wrong, what is the reason for not adding it?

Thanks in advance.

Latest Update(13.06.2015)- Part 2, page 342

In the book, we are adding a step for checking the feature of "a user can add post after login". The code is like this-

@when(u'we add a new entry with "{title}" and "{text}" as the title and text')
def add(context, title, text):
    context.page = context.client.post(
        '/add',
        data = dict(username=title, password=text),
        follow_redirects=True)
    assert context.page

The data variable should be assigned with the dict like this-

data = dict(title=title, text=text)

The code is ok in the course repository.

Real Python Part 2, Hello World App, Pages 505-515

When I attempted the last exercise starting on Page 511 (Templates), my betterhello.html for the better function would not render in my browser, and I kept receiving a "TemplateDoesNotExist at ..." error. I could not figure out where I was going wrong until I went to the RealPython_Book2_Exercises directory that I had, navigated to your project, and started the server to find that the page worked in your project! I then started copying and pasting the 6 or so files of code one by one until the betterhello.html file rendered at localhost:8000/better/. I had the exact same code EXCEPT in the settings.py file (under the "hello_world_project" directory) where there was a TEMPLATES = [....] list in my file where there was not one in yours (starting at line 64 or so). When I deleted this entire list, my betterhello.html file rendered at localhost:8000/better/ . The TEMPLATES list python code looks like this:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Looks like they updated some functionality after the book was written. (I also had the same Django Version 1.8.2).

missing charactor in code

In book 2, page 513.

The about function in the view returns some text and a link, but the link (anchor tag) is not closed properly.

"Back Home</a"

Missing > at the end

EDIT

book 2 page 557. The code showing the added Bootstrap Grid System is missing a closing div. the

is not closed as far as I can tell.

EDIT 2

In book 2 page 609 it says
"the relationship is the same for Django templates as it is for Jinga templates
in Flask." Shouldn't it be Jinja, not jinga?

#EDIT 3 #
In book 3 page 12 the last line says:
"you have any suggestions or feedback, please contact is."
it should probably be us, not is.

EDIT 4

Last chapter in book 2.
I probably need to go through the chapter again to determine if the error was on my end (which I suspect it is), but I got an error when i tried to create an account because the table didn't exist (payments_user, i think) and had to run syncdb again.

#EDIT 5 #
Page 590

line 21 contain "</script>" but there's no open script tag for it to close. Commenting that line out fixed the code.

Book 2 - Page 151+

There is inconsistent naming of the tasks table. First, on page 151, when the table is created, you call

__tablename__ = "tasks"

Starting on page 155, you call that very same table ftasks.

It's not really a problem, but it's still confusing.

Real Python Python Part 2, Page 385

Line 19 in the code block:

youtube_service.GetYouTubePlaylistVideoFeed(playlist_url) returns a "No Longer Available" error (410). I have crawled over Google and can't find why I am being returned this error. I am curious to see if anyone else can replicate it. I tried hermanmu and my own youtube user id and I couldn't get it to work. Thanks!

About web-crawling in hackernews

I have been trying to crawl on hackernews according to the code provided. I have faced some problem. I have reconstructed the code in spider.py like this-

From

from scrapy.spider import BaseSpider
...............
class MySpider(BaseSpider):
.........

To

from scrapy.spiders import Spider
..................
class MySpider(Spider):

and than it has worked. Is this a problem? Should i make a pull request?

Another question about the output of the crawler- Here is the output:

2015-09-15 19:30:04 [scrapy] INFO: Scrapy 1.0.3 started (bot: hackernews)
2015-09-15 19:30:04 [scrapy] INFO: Optional features available: ssl, http11
2015-09-15 19:30:04 [scrapy] INFO: Overridden settings: {'NEWSPIDER_MODULE':'hackernews.spiders', 'SPIDER_MODULES': ['hackernews.spiders'],'BOT_NAME': 'hackernews'}
2015-09-15 19:30:04 [scrapy] INFO: Enabled extensions: CloseSpider, TelnetConsole, LogStats, CoreStats, SpiderState
2015-09-15 19:30:04 [scrapy] INFO: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, RedirectMiddleware, CookiesMiddleware,ChunkedTransferMiddleware, DownloaderStats
2015-09-15 19:30:04 [scrapy] INFO: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
2015-09-15 19:30:04 [scrapy] INFO: Enabled item pipelines:
2015-09-15 19:30:04 [scrapy] INFO: Spider opened
2015-09-15 19:30:04 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2015-09-15 19:30:04 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6023
2015-09-15 19:30:04 [scrapy] INFO: Closing spider (finished)
2015-09-15 19:30:04 [scrapy] INFO: Dumping Scrapy stats:
{'finish_reason': 'finished','finish_time': datetime.datetime(2015, 9, 15, 13, 30, 4, 895000), 'log_count/DEBUG': 1,'log_count/INFO': 7,'start_time': datetime.datetime(2015, 9, 15, 13, 30, 4, 886000)}
2015-09-15 19:30:04 [scrapy] INFO: Spider closed (finished)

Is the output ok? I can't understand the meaning of the output. Shouldn't we see some title and text?

Looping over the function in tasks.html

I am at chapter 11 and i have applied error handling parts. But i am having problem while adding new tasks. The error is showing that

'function' object is not iterable

We are looping over the function in tasks.html while adding task-

 {% for task in open_tasks %}
        <tr>
           <td width="200px">{{ task.name }}</td>
            ...................
                 <td>
                   <a href="{{ url_for('delete_entry', task_id = task.task_id) }}">Delete</a>
                <a href="{{ url_for('complete', task_id = task.task_id) }}">Mark as Complete</a>
                 </td>
  </tr>
 {% endfor %}

The operation for closing tasks are functioning alright though.

I have googled but couldn't able to find any solution. Plus, as far as i know in python 'function' object is not iterable.

The problem wouldn't exist (may be) if we declare open_tasks and closed_tasks as a variable (like previous chapters) within task() function in views.py instead of defining two functions (open_tasks() and closed_tasks()) for the purpose.

Problem finding "jquery-1.11.1.min.js"

Hello, i am in at Chapter 13, page 215. It says my static folder should be look like this-

static
    css
       bootstrap.min.css
    js
       jquery-1.11.1.min.js
       bootstrap.min.js
    styles.css

I have downloaded Bootstrap files from this link- bootstrap_download. But i couldn't find any jquery-1.11.1.min.js file in these.

issue at Chapter 10 Page 171

I have edited the controller likewise the book said-

new_task = Task(
    form.name.data,
    form.due_date.data,
    form.priority.data,
    datetime.datetime.utcnow(),
    '1',
    '1' )

But while i ran the app, there occurred an error which points out that i was assigning an integer type to posted_date which should be a date type. So i have reconfigured the code like this-

new_task = Task(
            form.name.data,
            form.due_date.data,
            form.priority.data,
            '1',
            datetime.datetime.utcnow(),
            '1'
            )

And now it works.

Typo in Real Python Part 2, Page 277

Near the bottom of page 277, I believe there is a typo when discussing where the errorhandler code should be located:

"Update project/views.py:"

I think it should be:

"Update project/init.py:"

Thank you!

web2py section 22.11 Notes

Trying to update the controller default.py with a function for the note(s) page... my code looks (as far as I can tell) the same as shown here in the repo, line 26 but I am getting an error ticket when I try to actually access the page:

File "/home/memilanuk/web2py/applications/py2manager/controllers/default.py", line 57, in note
  form = crud.create(db.note) if auth.user else "Login to Post to the Project"
NameError: global name 'crud' is not defined

Not sure if its a version thing; I'm using web2py 2.12.3 on pythonanywhere.com, vs. 2.8.2 as used in the book. Web2py is supposed to be pretty good about backwards compatibility, and I thought crud was a standard feature...?

Real Python Python Part 2, Page 392

Typo in first sentence of first paragraph under Paragraph Header Google Directions API, "between to points" should be "two". Thanks! I'm loving these books!

Real Python Part 2, Page 486

The second socrata project only loops through one page, and I can't find any errors in my code (comparing it to the files provided). Where exactly should the "for looping" be occuring, or is the rule what sets the "for loop"? Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.