Code Monkey home page Code Monkey logo

microblog's Introduction

Welcome to Microblog!

This is an example application featured in my Flask Mega-Tutorial. See the tutorial for instructions on how to work with it.

The version of the application featured in this repository corresponds to the 2024 edition of the Flask Mega-Tutorial. You can find the 2018 and 2021 versions of the code here. And if for any strange reason you are interested in the original code, dating back to 2012, that is here.

microblog's People

Contributors

miguelgrinberg 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  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

microblog's Issues

TypeError: cannot concatenate 'str' and 'NoneType' objects

I'm a Chinese, and my system language is ZH_cn. So microblog went wrong to get best matched language. Full Traceback is behind:

TypeError: cannot concatenate 'str' and 'NoneType' objects
127.0.0.1 - - [28/Jan/2014 17:34:20] "GET /login?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
127.0.0.1 - - [28/Jan/2014 17:34:20] "GET /login?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
127.0.0.1 - - [28/Jan/2014 17:34:20] "GET /login?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
127.0.0.1 - - [28/Jan/2014 17:34:20] "GET /login?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
127.0.0.1 - - [28/Jan/2014 17:34:20] "GET /login?__debugger__=yes&cmd=resource&f=source.png HTTP/1.1" 200 -
127.0.0.1 - - [28/Jan/2014 17:34:20] "GET /login?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -

I found this works:
view.py:

@babel.localeselector
def get_locale():
    return request.accept_languages.best_match(LANGUAGES.keys())

change to >>

    return request.accept_languages.best_match(LANGUAGES.keys()) or 'en'

But I don't know is it a good way or not.

No such file or directory after adding Logging db_migrate

I followed your great tutorial (thanks for that great one) and i'm now on Part 8. I noticed that i become a

No such file or directory Error
for the microblog.log file. It seems to look inside the app directory for the tmp Directory and inside there for the log file. Strange is that this only happens in the db_migrate file.
The config.py and the init.py are like the ones in your repository.

bootstrap base.html dose not align

in base.html,

<a class="brand"
In safari and firefox, this will make microblog index and other nav links not aligned horizontally.

changed to
<a class="navbar-brand"

will solve it

First migration not working

Hey,

First of all, I want to thank you for the wonderful tutorial 👍

On my computer, when I run the first migration.

I don't have the same file as you. I do the order explained on the blog post:

  1. Create class user
  2. python db_create.py
  3. python db_migrate.py

I have an empty migration file.

If I do:

  1. python db_create.py
  2. Create class user
  3. python db_migrate.py

The file is the good one. It seems logical to me. What do you think?

Cheers,
Alexis.

chapter 7.3 error pages, put the FLASK_DEBUG back to 0

just a comment, in chapter 7.3, we put the app into debug FLASK_DEBUG=1 and then we build the custom 404 and 500 pages.
One note you might put into the chapter is to put FLASK_DEBUG=0 so we actually see the error pages.

thanks :)
I'm enjoying the book

ImportError: cannot import name 'app'

 Hello,miguel。I have finished your awesome "dog book" three weeks ago, and my code  bases on your  code. The 'app' is created in app/__init__.py, 
 Now I want  to add the full-text search function,but i don't know how to import 'app'.When i tried  to import it directly  like"from app import app", it didn't work and "ImportError: cannot import name 'app'" came out. i have try google and stackoverflow , but there were not helpful answer.
so i ask you for help. My english is not very well, hope you can understand what i say.Have a nice day!

Application fails immediately when accessed.

From the same build circumstances as mentioned in issue #1

Any attempt to connect to http://127.0.0.1:5000/ causes the stack trace listed below.

As evidenced by the previous issue reports, I tried to ensure that no extraneous deficiencies are to blame. The stack trace shows that the defect arises very early in the execution, so I suspect the cause lies within recent changes to one of the required dependencies.

Stack trace:
127.0.0.1 - - [28/Jun/2013 19:20:02] "GET / HTTP/1.1" 500 -
Traceback (most recent call last):
File "/home/yourself/evalOfFlask/flask/lib/python2.7/site-packages/flask/app.py", line 1836, in call
return self.wsgi_app(environ, start_response)
File "/home/yourself/evalOfFlask/flask/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/home/yourself/evalOfFlask/flask/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/yourself/evalOfFlask/flask/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/home/yourself/evalOfFlask/flask/lib/python2.7/site-packages/flask/app.py", line 1479, in full_dispatch_request
response = self.process_response(response)
File "/home/yourself/evalOfFlask/flask/lib/python2.7/site-packages/flask/app.py", line 1693, in process_response
self.save_session(ctx.session, response)
File "/home/yourself/evalOfFlask/flask/lib/python2.7/site-packages/flask/app.py", line 837, in save_session
return self.session_interface.save_session(self, session, response)
File "/home/yourself/evalOfFlask/flask/lib/python2.7/site-packages/flask/sessions.py", line 326, in save_session
val = self.get_signing_serializer(app).dumps(dict(session))
File "/home/yourself/evalOfFlask/flask/lib/python2.7/site-packages/itsdangerous.py", line 525, in dumps
payload = want_bytes(self.dump_payload(obj))
File "/home/yourself/evalOfFlask/flask/lib/python2.7/site-packages/itsdangerous.py", line 738, in dump_payload
json = super(URLSafeSerializerMixin, self).dump_payload(obj)
File "/home/yourself/evalOfFlask/flask/lib/python2.7/site-packages/itsdangerous.py", line 510, in dump_payload
return want_bytes(self.serializer.dumps(obj))
File "/home/yourself/evalOfFlask/flask/lib/python2.7/site-packages/flask/sessions.py", line 85, in dumps
return json.dumps(_tag(value), separators=(',', ':'))
File "/home/yourself/evalOfFlask/flask/lib/python2.7/site-packages/flask/json.py", line 126, in dumps
rv = _json.dumps(obj, **kwargs)
File "/usr/lib/python2.7/json/init.py", line 238, in dumps
**kw).encode(obj)
File "/usr/lib/python2.7/json/encoder.py", line 203, in encode
chunks = list(chunks)
File "/usr/lib/python2.7/json/encoder.py", line 428, in _iterencode
for chunk in _iterencode_dict(o, _current_indent_level):
File "/usr/lib/python2.7/json/encoder.py", line 402, in _iterencode_dict
for chunk in chunks:
File "/usr/lib/python2.7/json/encoder.py", line 326, in _iterencode_list
for chunk in chunks:
File "/usr/lib/python2.7/json/encoder.py", line 402, in _iterencode_dict
for chunk in chunks:
File "/usr/lib/python2.7/json/encoder.py", line 326, in _iterencode_list
for chunk in chunks:
File "/usr/lib/python2.7/json/encoder.py", line 436, in _iterencode
o = _default(o)
File "/home/yourself/evalOfFlask/flask/lib/python2.7/site-packages/flask/json.py", line 83, in default
return _json.JSONEncoder.default(self, o)
File "/usr/lib/python2.7/json/encoder.py", line 178, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: lu'Please log in so as to access this page.' is not JSON serializable

error: sudo service nginx reload

Hi @miguelgrinberg thanks for your help!
Now I am trying to deploy the microblog in the vagrant ubuntu server.

After I created nginx configuration file for Microblog file by the command:sudo nano /etc/nginx/sites-enabled/microblog,
and input the following text in this file which mentioned in your book.

server {
    # listen on port 80 (http)
    listen 80;
    server_name _;
    location / {
        # redirect any requests to the same URL but on https
        return 301 https://\$host\$request_uri;
    }
}
server {
    # listen on port 443 (https)
    listen 443 ssl;
    server_name _;
    # location of the self-signed SSL certificate
    ssl_certificate /home/ubuntu/microblog2/certs/cert.pem;
    ssl_certificate_key /home/ubuntu/microblog2/certs/key.pem;
    # write access and error logs to /var/log
    access_log /var/log/microblog_access.log;
    error_log /var/log/microblog_error.log;
    location / {
        # forward application requests to the gunicorn server
        proxy_pass http://127.0.0.1:8000;
        proxy_redirect off;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        }
    location /static {
        # handle static files directly, without forwarding to the application
        alias /home/ubuntu/microblog2/static;
        expires 30d;
        }
 }

I want to ask that
(1): the directory of microblog in ubuntu is microblog, why you set the /home/ubuntu/microblog2/ in this file.

(2) there is error, after I run the command: sudo service nginx reload

u-xenial:~/microblog$ sudo nano /etc/nginx/sites-enabled/microblog
(venv) ubuntu@ubuntu-xenial:~/microblog$ sudo service nginx reload
Job for nginx.service failed because the control process exited with error code. See "systemctl status nginx.service" and "journalctl -xe" for details.
(venv) ubuntu@ubuntu-xenial:~/microblog$ systemctl status nginx.service
● nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) (Result: exit-code) since Tue 2017-12-26 03:46:48 UTC; 2h 7min ago
  Process: 4632 ExecReload=/usr/sbin/nginx -g daemon on; master_process on; -s reload (code=exited, status=1/FAILURE)
 Main PID: 3774 (nginx)
    Tasks: 3
   Memory: 2.2M
      CPU: 373ms
   CGroup: /system.slice/nginx.service
           ├─3774 nginx: master process /usr/sbin/nginx -g daemon on; master_process on
           ├─3775 nginx: worker process                           
           └─3776 nginx: worker process                           

Dec 26 05:51:46 ubuntu-xenial systemd[1]: Started A high performance web server and a reverse proxy server.
Dec 26 05:52:09 ubuntu-xenial systemd[1]: Reloading A high performance web server and a reverse proxy server.
Dec 26 05:52:09 ubuntu-xenial nginx[4565]: nginx: [emerg] unknown log format "error_log" in /etc/nginx/sites-enabled/microblog:19
Dec 26 05:52:09 ubuntu-xenial systemd[1]: nginx.service: Control process exited, code=exited status=1
Dec 26 05:52:09 ubuntu-xenial systemd[1]: Reload failed for A high performance web server and a reverse proxy server.
Dec 26 05:52:56 ubuntu-xenial systemd[1]: Started A high performance web server and a reverse proxy server.
Dec 26 05:54:21 ubuntu-xenial systemd[1]: Reloading A high performance web server and a reverse proxy server.
Dec 26 05:54:21 ubuntu-xenial nginx[4632]: nginx: [emerg] unknown log format "error_log" in /etc/nginx/sites-enabled/microblog:19
Dec 26 05:54:21 ubuntu-xenial systemd[1]: nginx.service: Control process exited, code=exited status=1
Dec 26 05:54:21 ubuntu-xenial systemd[1]: Reload failed fo

ch: 22 -- adding tasks

One note on chapter 22 -- after adding the Database model, you might want to add a note to "flask db migrate" and "flask db upgrade" -- by that point I'm sure we should know that, but I still managed to not run the migration.

Also -- something of interest -- I had an error in tasks.py, so when I attempted to run an export, it created the task and sent it along to redis; however, because of the error in tasks.py, redis bombed and moved the task to the 'failed' queue. However, my task doesn't realize that, so it's stuck at "0".

I'm going to add some code to check if the task is in the 'failed' queue and add messaging.

Thanks -- really enjoyed the book thus far.

TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given

Hi @miguelgrinberg thanks for your help, and I have studied chapter16 about search text:

But there is error when I use your code as following:

[2017-12-25 17:23:38,688] ERROR in app: Exception on /search [GET]
Traceback (most recent call last):
File "/anaconda3/envs/venv/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/anaconda3/envs/venv/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/anaconda3/envs/venv/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/anaconda3/envs/venv/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/anaconda3/envs/venv/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/anaconda3/envs/venv/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functionsrule.endpoint
File "/anaconda3/envs/venv/lib/python3.6/site-packages/flask_login/utils.py", line 228, in decorated_view
return func(*args, **kwargs)
File "/Users/k.den/microblog/app/main/routes.py", line 152, in search
if not g.search_form.validate():
File "/anaconda3/envs/venv/lib/python3.6/site-packages/wtforms/form.py", line 310, in validate
return super(Form, self).validate(extra)
File "/anaconda3/envs/venv/lib/python3.6/site-packages/wtforms/form.py", line 152, in validate
if not field.validate(self, extra):
File "/anaconda3/envs/venv/lib/python3.6/site-packages/wtforms/fields/core.py", line 204, in validate
stop_validation = self._run_validation_chain(form, chain)
File "/anaconda3/envs/venv/lib/python3.6/site-packages/wtforms/fields/core.py", line 224, in _run_validation_chain
validator(form, self)
TypeError: init() takes from 1 to 2 positional arguments but 3 were given
127.0.0.1 - - [25/Dec/2017 17:23:38] "GET /search?q= HTTP/1.1" 500 -

The code is shown as following:

@bp.route('/search')
@login_required
def search():
    if not g.search_form.validate():
        return redirect(url_for('explore'))
    page = request.args.get('page', 1, type=int)
    posts, total = Post.search(g.search_form.q.data, page,
                               current_app.config['POSTS_PER_PAGE'])
    next_url = url_for('main.search', q=g.search_form.q.data, page=page + 1) \
        if total > page * current_app.config['POSTS_PER_PAGE'] else None
    prev_url = url_for('main.search', q=g.search_form.q.data, page=page - 1) \
        if page > 1 else None
    return render_template('search.html', title='Search', posts=posts,
                           next_url=next_url, prev_url=prev_url)

Could microblog support python3?

I'm a python beginner,it seems python3 will be the trend of python though python2 is dominant nowdays,so I study python3I want to use python to write a personal blog,so I want to study from microblogBut micro blog is written in python2,so could you support python3?And flask also support python3(maybe some plugins don't support)...

Documentation not available

The (excellent!) tutorial for which this project appears to be a working example is currently unavailable because of an internal server error. To avoid this in the future, it might be nice to just put the tutorial in the same repo.

Problem after login

After login with my google openid, i see this traceback

AttributeError

AttributeError: '_QueryProxy' object has no attribute 'paginate'
Traceback (most recent call last)

File "C:\Python27\lib\site-packages\flask\app.py", line 1701, in __call__

return self.wsgi_app(environ, start_response)

File "C:\Python27\lib\site-packages\flask\app.py", line 1689, in wsgi_app

response = self.make_response(self.handle_exception(e))

File "C:\Python27\lib\site-packages\flask\app.py", line 1687, in wsgi_app

response = self.full_dispatch_request()

File "C:\Python27\lib\site-packages\flask\app.py", line 1360, in full_dispatch_request

rv = self.handle_user_exception(e)

File "C:\Python27\lib\site-packages\flask\app.py", line 1358, in full_dispatch_request

rv = self.dispatch_request()

File "C:\Python27\lib\site-packages\flask\app.py", line 1344, in dispatch_request

return self.view_functions[rule.endpoint](**req.view_args)

File "C:\Python27\lib\site-packages\flask_login.py", line 515, in decorated_view

return fn(*args, **kwargs)

File "C:\Users\Pablo2M\Desktop\microblog-0.14\app\views.py", line 51, in index

posts = g.user.followed_posts().paginate(page, POSTS_PER_PAGE, False)

AttributeError: '_QueryProxy' object has no attribute 'paginate'

The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.

To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.

You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:

dump() shows all variables in the frame
dump(obj) dumps all that's known about the object

These are the packages that I have installed:

C:\Users\Pablo2M>pip list
Babel (0.9.6)
blinker (1.2)
coverage (3.6)
decorator (3.4.0)
Flask (0.9)
Flask-Babel (0.8)
Flask-Login (0.1.3)
Flask-Mail (0.8.2)
Flask-OpenID (1.1.1)
Flask-SQLAlchemy (0.16)
Flask-WhooshAlchemy (0.54a)
Flask-WTF (0.9.4)
Warning: cannot find svn location for flup==1.0.3.dev-20110405
flup (1.0.3.dev-20110405)
guess-language (0.2)
gunicorn (0.17.2)
itsdangerous (0.23)
Jinja2 (2.6)
MarkupSafe (0.18)
oauthlib (0.6.1)
pip (1.5)
PyPump (0.4)
python-dateutil (2.2)
python-openid (2.2.5)
pytz (2013b)
requests (1.2.3)
requests-oauthlib (0.4.0)
setuptools (2.0.2)
six (1.5.2)
speaklater (1.3)
SQLAlchemy (0.7.9)
sqlalchemy-migrate (0.7.2)
Tempita (0.5.1)
Werkzeug (0.8.3)
Whoosh (2.4.1)
WTForms (1.0.3)

Can you help me?

ImportError: No module named migrate.versioning?

After pip install -r requirements.txt and python db_create.py, I still get the following? Which library is it taken from Flask-Migrate, Migrate?

    from migrate.versioning import api
ImportError: No module named migrate.versioning

I did get:

ld: library not found for -lgcc_s.10.5
collect2: ld returned 1 exit status
error: command '/usr/local/bin/gcc-4.2' failed with exit status 1

EDIT:
OK it is the sqlalchemy-migrate==0.9.2 not installed, but not sure why pip install -r requirements.txt didnt do it for me?

chap 23: api

need to add that we put the following into init.py
otherwise, i got 404 errors
thanks

from app.api import bp as api_bp
app.register_blueprint(api_bp, url_prefix='/api')

Error on running individual files in the app package.

Hi, I'm new to python and also this might not be the best place to ask this but, i am struggling.
When i run the the app by executing the run.py file, it works fine.
But, before this i tried to run views.py, just to check if i had made any syntax error, it gave this:

ImportError: No module named app

Can we import the package inside the package itself ?

8.3 Error when running 'flask db migrate'

I got the following error when running 'flask db migrate -m "followers"'
NameError: name 'followers' is not defined
I removed the changes to the User class then ran the migration and it works fine so just seems to be an error in the order of operations.

BTW, thanks for the great update to the tutorial!

setup instructions don't mention python.h dependency

I set up a brand new Ubuntu 12.04 LTS system in a virtual machine and ran the full set of apt-get updates, upgrades and dist-upgrades.

I then downloaded and decompressed the zip version of this project and ran:
./setup.py

sqlalchemy and coverage both choke on lack of python.h

The fix is to run :
sudo apt-get -y install python-dev

KeyError: 'POSTS_PER_PAGE'

hi @miguelgrinberg thanks for your great book.

I am studying the chapter 9.4 Pagination of Blog

I almost copy you code about Pagination of Blog.
But after I click the explore, there is error as following in the terminal. Before the chapter 9.4, everything gone well.
The code in routes about explore:

@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
@login_required
def index():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(body=form.post.data, author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Your post is now live')
        return redirect(url_for('index'))
    page = request.args.get('page', 1, type=int)
    posts = current_user.followed_posts().paginate(
        page, app.config['POSTS_PER_PAGE'], False)
    next_url = url_for('explore', page=posts.next_num) \
        if posts.has_next else None
    prev_url = url_for('explore', page=posts.prev_num) \
        if posts.has_prev else None
    return render_template('index.html', title='Home', form=form,
                           posts=posts.items, next_url=next_url,
                           prev_url=prev_url)


@app.route('/explore')
@login_required
def explore():
    page = request.args.get('page', 1, type=int)
    posts = Post.query.order_by(Post.timestamp.desc()).paginate(
        page, app.config['POSTS_PER_PAGE'], False)
    next_url = url_for('explore', page=posts.next_num) \
        if posts.has_next else None
    prev_url = url_for('explore', page=posts.prev_num) \
        if posts.has_prev else None
    return render_template('index.html', title='Explore', posts=posts.items,
                           next_url=next_url, prev_url=prev_url) 

The error information in terminal as following:

127.0.0.1 - - [22/Dec/2017 23:32:07] "GET /explore HTTP/1.1" 500 -
[2017-12-22 23:32:08,138] ERROR in app: Exception on /index [GET]
Traceback (most recent call last):
File "/anaconda3/envs/venv/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/anaconda3/envs/venv/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/anaconda3/envs/venv/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/anaconda3/envs/venv/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/anaconda3/envs/venv/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/anaconda3/envs/venv/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functionsrule.endpoint
File "/anaconda3/envs/venv/lib/python3.6/site-packages/flask_login/utils.py", line 228, in decorated_view
return func(*args, **kwargs)
File "/Users/kd/microblog/app/routes.py", line 31, in index
page, app.config['POSTS_PER_PAGE'], False)
KeyError: 'POSTS_PER_PAGE'

Chapter 8 models.py import typo

In app/models.py, you've got a bit of a typo in your imports: from werkzeug import generate_password_hash, check_password_hash should be from werkzeug.security import generate_password_hash, check_password_hash.

Cheers!

elasticsearch.exceptions.ConnectionError

Cannot seem to get a connection to the elasticsearch server started. I have tried the example setup in the python shell, import the module, pass the server address and port to the instance of es, however, I get the following error:

elasticsearch.exceptions.ConnectionError
elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x73fc8a50>: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x73fc8a50>: Failed to establish a new connection: [Errno 111] Connection refused)

I am running Microblog off a Raspberry Pi 3 server that I have connected remotely through SSH. I checked to see if the port was open with nmap through SSH, and it states:

Starting Nmap 7.40 ( https://nmap.org ) at 2017-12-22 13:36 UTC
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00029s latency).
Other addresses for localhost (not scanned): ::1
PORT     STATE  SERVICE
9200/tcp closed wap-wsp

Nmap done: 1 IP address (1 host up) scanned in 0.35 seconds

All of my testing that I have done is through an SSH shell into the Pi. I also have checked with sudo netstat -tuplen to see if port 9200 was open, and it was not shown.

I installed elasticsearch as described in Chapter 16 through pip.

Any assistance would be appreciated.

TypeError: 'AnonymousUserMixin' object is not callable

below is my code

from app import db

class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
nickname = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
posts = db.relationship('Post', backref = 'author',lazy ='dynamic')

# just return True unless the object represents a user that should not be allowed to authenticate for some reason.
@property
def is_authenticated(self):
    return True

#should return True for users unless they are inactive e.g they have been banned
@property
def is_active(self):
 	return False

#should return True for users that are not supposed to log in to the system

@property
def is_anonymous(self):
    return False


def get_id(self):
 	 try:
 		return unicode(self.id) #for python 2
     except NameError:
    	return str(self.id) #for python 3   


def __repr__(self):
     return '<User %r>' % (self.nickname)

html issues.maybe jinja....

I almost write the demo with your mega-flask tutorial except the localization.

one month ago,i just run the demo perfectly,but when i rewrite it recently ,i made a exception.

here it is:

File "/home/fly/dev/py2/microblog/app/templates/base.html", line 28, in top-level template code
$(destId).text("{{('Error: Could not contact server.') }}");
UndefinedError: '
' is undefined

so i just delete the '_' on line 28 (in your program is line 31) on base.html

but , it occurs a new exception,i also delete '_' in the line.

File "/home/fly/dev/py2/microblog/app/templates/post.html", line 6, in template

{{ ('%(nickname)s said %(when)s:', nickname='%s' % (url_for('user', nickname=post.author.nickname), post.author.nickname), when=momentjs(post.timestamp).fromNow() ) }}

TemplateSyntaxError: expected token ')', got '='

I googled it but can't find a similar answer,so could your test it ?maybe jinja's grammer has changed?

my environment is debian8_64bit, python 2.7.9, chrome51, jinja2.8
Thanks !

Error in Listing 5.1 (UserMixin introduced later)

Hi Miguel,

I just realized, that you have class User(UserMixin, db.Model): in Listing 5.1.

But only in Listing 5.3, after installing flask-login UserMixin gets introduced:

from flask_login import UserMixin
class User(UserMixin, db.Model):
# ...

Best regards
Sven

http: error

I have learned chapter 14 in your book 《Flask Web Development》,about use HTTPie test Web Server。when I input "http GET http://127.0.0.1:5000/api/v1.0/posts" on Windows. I get
"http: error: ConnectionError: HTTPConnectionPool(host:'127.0.0.1', port=5000):Max retries exceeded with url:/api/v1.0/posts (Caused by <class 'socket.'error>:[Errno 10061])

I don't know how to slove this problem。 Thank you !

There is no user register function.

Hello, I follow your tutorials and repositories, and find that there no user register function though your repositories have user login-in function. Could you show a example include user register function. It will be very necessary for newbie as me.
Thankyou very much!

Flask-OpenID seems not to be compatible with Python3 despite use of updated package

I'm trying to get microblog working in a virtualenv (I've also tried without) on my Mac with El Capitan. I'm attempting to run python3 db_create.py && python3 db_migrate.py. I've tried with Flask-OpenID versions 1.2.1 and the supposedly Python 3-compatible 1.2.5, to no avail. Here's my stack trace:

/Users/boesene/Desktop/microblog/venv/lib/python3.6/site-packages/six.py:79: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
  __import__(name)
/Users/boesene/Desktop/microblog/venv/lib/python3.6/site-packages/jinja2/filters.py:24: DeprecationWarning: Flags not at the start of the expression \w+(?u)
  _word_re = re.compile(r'\w+(?u)')
Traceback (most recent call last):
  File "db_create.py", line 5, in <module>
    from app import db
  File "/Users/boesene/Desktop/microblog/app/__init__.py", line 6, in <module>
    from flask_openid import OpenID
  File "/Users/boesene/Desktop/microblog/venv/lib/python3.6/site-packages/flask_openid.py", line 26, in <module>
    from openid.store.filestore import FileOpenIDStore
  File "/Users/boesene/Desktop/microblog/venv/lib/python3.6/site-packages/openid/__init__.py", line 52, in <module>
    if len(version_info) != 3:
TypeError: object of type 'map' has no len()

It looks like a pretty simple python3 incompatibility issue, even though I'm using a version of Flask-OpenID which is allegedly compatible with 3.

How could I go about getting around this problem?

chapter 5 user login page 50

chapter 5 user login page 50 , not write
from werkzeug import check_password_hash , generate_password_hash in example book :)
i know is the very small issue but I see remember you

errors

pydevd.py", line 1784, in run
pydev_imports.execfile(file, globals, locals) # execute the script
microblog\run.py", line 2, in
from app import app
microblog\app__init__.py", line 4, in
from flask.ext.sqlalchemy import SQLAlchemy
flask\exthook.py", line 87, in load_module
raise ImportError('No module named %s' % fullname)
ImportError: No module named flask.ext.sqlalchemy

accessing app from command line after chapter 15

if I want to import the app from the terminal after chapter 15, how should I go about that?
for instance, attempting the following from termina

from app.search import add_to_index, remove_from_index, query_index for post in Post.query.all(): add_to_index('posts', post) query_index('posts', 'one two three four five', 1, 100)
results in 'NameError: name 'Post' is not defined'
I attempted 'from app.models import Post' but then I get RuntimeError: No application found. Either work inside a view function or push an application context.

I'm now attempting to reindex (chapter 16) and cannot from terminal.

Thanks

Flask Admin

Is it possible to add Flask_admin to this tutorial?
It's a very useful and powerful extension.
It will be very interesting to see how you would use it with this new Flask structure.

no such table: user

after running chapter 8 -- follower, contacts and friends
doing the tests.py, etc.
I attempt to login and 'follow' but get a "sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: user"
i tried 'sqlite3' on terminal and the only table in sqlite app.db is alembic_version
I attempt 'flask db downgrade' and get "no such table: followers"

I'm going to keep looking, but is possible the tests.py emptied the database?

the beginning of my tests.py file:

class UserModelCase(unittest.TestCase):
    def setUp(self):
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()

a question on rebuilding the migrations

I just finished chapter 15 -- great book and chapter.

Previously, I was building the application myself, but with the changes to chapter 15, I pulled the repo and am working from that. To get the app running, I had to clear the migrations and rerun them, as the repo app didn't have an app.db

Is there a technique for resetting / rebuilding a migration?

Thanks

chapter 5 - import werkzeug into models.py not explicitly mentioned

In the book, chapter 5.3 mentions importing werkzeug in the python terminal; however, it doesn't seem to explicitly mention to include the library in models.py.

I got a 'could not find generate_password_hash' until I looked at the git repo

just FYI -- great book.

also, if I misread or otherwise -- my apologies.

Problem decoding utf-8 json response in the translate.py model

When I try to load the Microsoft Translate response into the json module it throws an error

The end of the stack trace looks like:

....\Lib\json\decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

A bit of debugging revealed that the response from microsoft includes BOM characters that cause the json libary to see the returned result as invalid. This is the line that has the issue.

    response = json.loads('{"response":' +
                          conn.getresponse().read().decode('utf-8') + '}')

I got around that by changing the decode like this:

    response = json.loads('{"response":' +
                          conn.getresponse().read().decode('utf-8-sig') + '}')

'utf-8-sig' deals with the extra characters.

I am on windows 7 and am trying to figure out if this issue is related to that or other environmental elements. This seems like a problem someone else should have also had if it was related to the code in your tutorial.

chapter 16, form.py reference

just a typo I noticed.

Listing 16.7 references app/forms.py which you've moved to app/main/forms.py
Listing 16.8 references from app.forms import SearchForm when you when you want from app.main.forms

running the app without the typo fix gets a "app.forms not found"

thanks

tests failing :\

Hi Miguel - I think this is easier to communicate re those tests failing than hundreds of comments in your blog ;) ...

My tests are still failing and all seems to go back to that the SQLALCHEMY_DATABASE_URI doesnt seem to take effect within the tests.py, here's mine I've got so far -

tests.py:

#!bin/python
import os
import unittest
from datetime import datetime, timedelta

from config import basedir
from app import app, db
from app.models import User, Post

class TestCase(unittest.TestCase):

    def setUp(self):
        app.config['TESTING'] = True
        app.config['CSRF_ENABLED'] = False
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'test.db')
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()

    def test_avatar(self):
        u = User(nickname = 'john', email = '[email protected]')
        avatar = u.avatar(128)
        expected = 'http://www.gravatar.com/avatar/d4c74594d841139328695756648b6bd6'
        assert avatar[0:len(expected)] == expected

    def test_make_unique_nickname(self):
        u = User(nickname = 'john', email = '[email protected]')
        db.session.add(u)
        db.session.commit()
        nickname = User.make_unique_nickname('john')
        assert nickname != 'john'
        u = User(nickname = nickname, email = '[email protected]')
        db.session.add(u)
        db.session.commit()
        nickname2 = User.make_unique_nickname('john')
        assert nickname2 != 'john'
        assert nickname2 != nickname


    def test_follow(self):
        u1 = User(nickname='john', email='[email protected]')
        u2 = User(nickname='susan', email='[email protected]')
        db.session.add(u1)
        db.session.add(u2)
        db.session.commit()
        assert u1.unfollow(u2) == None
        u = u1.follow(u2)
        db.session.add(u)
        db.session.commit()
        assert u1.follow(u2) == None
        assert u1.is_following(u2)
        assert u1.followed.count() == 1
        assert u1.followed.first().nickname == 'susan'
        assert u2.followers.count() == 1
        assert u2.followers.first().nickname == 'john'
        u = u1.unfollow(u2)
        assert u != None
        db.session.add(u)
        db.session.commit()
        assert u1.is_following(u2) == False
        assert u1.followed.count() == 0
        assert u2.followers.count() == 0


    def test_follow_posts(self):
      # make four users
        u1 = User(nickname='john', email='[email protected]')
        u2 = User(nickname='susan', email='[email protected]')
        u3 = User(nickname='mary', email='[email protected]')
        u4 = User(nickname='david', email='[email protected]')
        db.session.add(u1)
        db.session.add(u2)
        db.session.add(u3)
        db.session.add(u4)
        # make four posts
        utcnow = datetime.utcnow()
        p1 = Post(body="post from john", author=u1, timestamp=utcnow + timedelta(seconds=1))
        p2 = Post(body="post from susan", author=u2, timestamp=utcnow + timedelta(seconds=2))
        p3 = Post(body="post from mary", author=u3, timestamp=utcnow + timedelta(seconds=3))
        p4 = Post(body="post from david", author=u4, timestamp=utcnow + timedelta(seconds=4))
        db.session.add(p1)
        db.session.add(p2)
        db.session.add(p3)
        db.session.add(p4)
        db.session.commit()
        # setup the followers
        u1.follow(u1) # john follows himself
        u1.follow(u2) # john follows susan
        u1.follow(u4) # john follows david
        u2.follow(u2) # susan follows herself
        u2.follow(u3) # susan follows mary
        u3.follow(u3) # mary follows herself
        u3.follow(u4) # mary follows david
        u4.follow(u4) # david follows himself
        db.session.add(u1)
        db.session.add(u2)
        db.session.add(u3)
        db.session.add(u4)
        db.session.commit()
        # check the followed posts of each user
        f1 = u1.followed_posts().all()
        f2 = u2.followed_posts().all()
        f3 = u3.followed_posts().all()
        f4 = u4.followed_posts().all()

        assert len(f1) == 3
        assert len(f2) == 2
        assert len(f3) == 2
        assert len(f4) == 1
        assert f1 == [p4, p2, p1]
        assert f2 == [p3, p2]
        assert f3 == [p4, p3]
        assert f4 == [p4]


if __name__ == '__main__':
    unittest.main()

The result when running :

$ python tests.py -v
test_avatar (__main__.TestCase) ... ok
test_follow (__main__.TestCase) ... ok
test_follow_posts (__main__.TestCase) ... FAIL
test_make_unique_nickname (__main__.TestCase) ... ok

======================================================================
FAIL: test_follow_posts (__main__.TestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "tests.py", line 108, in test_follow_posts
    assert len(f1) == 3
AssertionError

----------------------------------------------------------------------
Ran 4 tests in 3.210s

FAILED (failures=1)

With some debug output (prints f1 just before assert) :

$ python tests.py -v
test_avatar (__main__.TestCase) ... ok
test_follow (__main__.TestCase) ... ok
test_follow_posts (__main__.TestCase) ... [<Post u'tttttt'>]
FAIL
test_make_unique_nickname (__main__.TestCase) ... ok

the Post "tttttt" is actually from the app.db, not the test.db :

$ sqlite3 app.db 
SQLite version 3.6.20
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> select * from post;
1|tttttt|2014-05-27 07:33:27.915106|1

I have also printed the value of the app.config['SQLALCHEMY_DATABASE_URI'] within the function/s but it seems correct there, so I think that the db.session.add(x) actually seems to be taking the config from __init__.py (config import) instead of the setUp(self) function within the testClass.

Any clues what's going on or how else to debug what is really accessed when a DB session is created / committed ?

Alex

db_create.py fails due to missing dependency woosh-alchemy

From the same build circumstances as mentioned in issue #1

The installation instructions specify running db_create.py after running setup.py, however db_create.py complains that it lacks woosh-alchemy,

The fix is to uncomment line #20

subprocess.call([os.path.join('flask', bin, 'pip'), 'install', 'flask-whooshalchemy'])

question about chapter 4 Database: flask db migrate -m "posts table"

Thanks for your great e-book which I have brought it from your site.
Now I am studying the chapter 4, when run the following command in terminal(mac):
flask db migrate -m "posts table"

there is error:

(venv) A1706-084:microblog kd$ flask db migrate -m "posts table"

/anaconda3/envs/venv/lib/python3.6/site-packages/flask_sqlalchemy/init.py:774: UserWarning: Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. Defaulting SQLALCHEMY_DATABASE_URI to "sqlite:///:memory:".
'Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. '
INFO [alembic.runtime.migration] Context impl SQLiteImpl.
INFO [alembic.runtime.migration] Will assume non-transactional DDL.
Traceback (most recent call last):
File "/anaconda3/envs/venv/bin/flask", line 11, in
sys.exit(main())
File "/anaconda3/envs/venv/lib/python3.6/site-packages/flask/cli.py", line 513, in main
cli.main(args=args, prog_name=name)
File "/anaconda3/envs/venv/lib/python3.6/site-packages/flask/cli.py", line 380, in main
return AppGroup.main(self, *args, **kwargs)
File "/anaconda3/envs/venv/lib/python3.6/site-packages/click/core.py", line 697, in main
rv = self.invoke(ctx)
File "/anaconda3/envs/venv/lib/python3.6/site-packages/click/core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/anaconda3/envs/venv/lib/python3.6/site-packages/click/core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/anaconda3/envs/venv/lib/python3.6/site-packages/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/anaconda3/envs/venv/lib/python3.6/site-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/anaconda3/envs/venv/lib/python3.6/site-packages/click/decorators.py", line 17, in new_func
return f(get_current_context(), *args, **kwargs)
File "/anaconda3/envs/venv/lib/python3.6/site-packages/flask/cli.py", line 257, in decorator
return __ctx.invoke(f, *args, **kwargs)
File "/anaconda3/envs/venv/lib/python3.6/site-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/anaconda3/envs/venv/lib/python3.6/site-packages/flask_migrate/cli.py", line 90, in migrate
rev_id, x_arg)
File "/anaconda3/envs/venv/lib/python3.6/site-packages/flask_migrate/init.py", line 197, in migrate
version_path=version_path, rev_id=rev_id)
File "/anaconda3/envs/venv/lib/python3.6/site-packages/alembic/command.py", line 176, in revision
script_directory.run_env()
File "/anaconda3/envs/venv/lib/python3.6/site-packages/alembic/script/base.py", line 425, in run_env
util.load_python_file(self.dir, 'env.py')
File "/anaconda3/envs/venv/lib/python3.6/site-packages/alembic/util/pyfiles.py", line 81, in load_python_file
module = load_module_py(module_id, path)
File "/anaconda3/envs/venv/lib/python3.6/site-packages/alembic/util/compat.py", line 83, in load_module_py
spec.loader.exec_module(module)
File "", line 678, in exec_module
File "", line 219, in _call_with_frames_removed
File "migrations/env.py", line 87, in
run_migrations_online()
File "migrations/env.py", line 80, in run_migrations_online
context.run_migrations()
File "", line 8, in run_migrations
File "/anaconda3/envs/venv/lib/python3.6/site-packages/alembic/runtime/environment.py", line 836, in run_migrations
self.get_context().run_migrations(**kw)
File "/anaconda3/envs/venv/lib/python3.6/site-packages/alembic/runtime/migration.py", line 321, in run_migrations
for step in self._migrations_fn(heads, self):
File "/anaconda3/envs/venv/lib/python3.6/site-packages/alembic/command.py", line 156, in retrieve_migrations
revision_context.run_autogenerate(rev, context)
File "/anaconda3/envs/venv/lib/python3.6/site-packages/alembic/autogenerate/api.py", line 415, in run_autogenerate
self._run_environment(rev, migration_context, True)
File "/anaconda3/envs/venv/lib/python3.6/site-packages/alembic/autogenerate/api.py", line 427, in _run_environment
raise util.CommandError("Target database is not up to date.")
alembic.util.exc.CommandError: Target database is not up to date.

Could you tell me how to solve it, thanks!

AttributeError: class momentjs has no attribute '__call__'

From the same build circumstances as mentioned in closed issue #1

In trying to build and use this GitHub repository on its own, without reference to the foundation tutorial, I encounter the exception:

127.0.0.1 - - [30/Jun/2013 08:32:37] "GET /user/martinhbramwell HTTP/1.1" 500 -
Traceback (most recent call last):
File "/home/temp/Desktop/microblog-master/flask/lib/python2.7/site-packages/flask/app.py", line 1701, in call
return self.wsgi_app(environ, start_response)
File "/home/temp/Desktop/microblog-master/flask/lib/python2.7/site-packages/flask/app.py", line 1689, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/home/temp/Desktop/microblog-master/flask/lib/python2.7/site-packages/flask/app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "/home/temp/Desktop/microblog-master/flask/lib/python2.7/site-packages/flask/app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/temp/Desktop/microblog-master/flask/lib/python2.7/site-packages/flask/app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()
File "/home/temp/Desktop/microblog-master/flask/lib/python2.7/site-packages/flask/app.py", line 1344, in dispatch_request
return self.view_functionsrule.endpoint
File "/home/temp/Desktop/microblog-master/flask/lib/python2.7/site-packages/flask_login.py", line 650, in decorated_view
return func(_args, *_kwargs)
File "/home/temp/Desktop/microblog-master/app/views.py", line 128, in user
posts = posts)
File "/home/temp/Desktop/microblog-master/flask/lib/python2.7/site-packages/flask/templating.py", line 125, in render_template
context, ctx.app)
File "/home/temp/Desktop/microblog-master/flask/lib/python2.7/site-packages/flask/templating.py", line 107, in _render
rv = template.render(context)
File "/home/temp/Desktop/microblog-master/flask/lib/python2.7/site-packages/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File "/home/temp/Desktop/microblog-master/flask/lib/python2.7/site-packages/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/temp/Desktop/microblog-master/app/templates/user.html", line 2, in top-level template code
{% extends "base.html" %}
File "/home/temp/Desktop/microblog-master/app/templates/base.html", line 64, in top-level template code
{% block content %}{% endblock %}
File "/home/temp/Desktop/microblog-master/app/templates/user.html", line 13, in block "content"

{{ _('Last seen:') }} {{ momentjs(user.last_seen).calendar() }}


AttributeError: class momentjs has no attribute 'call'

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.