The Flask Mega-Tutorial Part XVIII: Deployment on Heroku

This is the eighteenth installment of the Flask Mega-Tutorial series, in which I'm going to deploy Microblog to the Heroku cloud platform.

For your reference, below is a list of the articles in this series.

Note 1: If you are looking for the legacy version of this tutorial, it's here.

Note 2: If you would like to support my work on this blog, or just don't have patience to wait for weekly articles, I am offering the complete version of this tutorial packaged as an ebook or a set of videos. For more information, visit courses.miguelgrinberg.com.

In the previous article I showed you the "traditional" way to host a Python application, and I gave you two actual examples of deployment to Linux based servers. If you are not used to manage a Linux system, you probably thought that the amount of effort that needs to be put into the task was big, and that surely there must be an easier way.

In this chapter I'm going to show you a completely different approach, in which you rely on a third-party cloud hosting provider to perform most of the administration tasks, freeing you to spend more time working on your application.

Many cloud hosting providers offer a managed platform on which applications can run. All you need to provide to have your application deployed on these platforms is the actual application, because the hardware, operating system, scripting language interpreters, database, etc. are all managed by the service. This type of service is called Platform as a Service, or PaaS.

Sounds too good to be true, right?

I will look at deploying Microblog to Heroku, a popular cloud hosting service that is also very friendly for Python applications. I picked Heroku not only because it is popular, but also because it has a free service level that will allow you to follow me and do a complete deployment without spending any money.

The GitHub links for this chapter are: Browse, Zip, Diff.

Hosting on Heroku

Heroku was one of the first platform as a service providers. It started as a hosting option for Ruby based applications, but then grew to support many other languages like Java, Node.js and of course Python.

Deploying a web application to Heroku is done through the git version control tool, so you must have your application in a git repository. Heroku looks for a file called Procfile in the application's root directory for instructions on how to start the application. For Python projects, Heroku also expects a requirements.txt file that lists all the module dependencies that need to be installed. After the application is uploaded to Heroku's servers through git, you are essentially done and just need to wait a few seconds until the application is online. It's really that simple.

The different service tiers Heroku offers allow you to choose how much computing power and time you get for your application, so as your user base grows you will need to buy more units of computing, which Heroku calls "dynos".

Ready to try Heroku? Let's get started!

Creating Heroku account

Before you can deploy to Heroku you need to have an account with them. So visit heroku.com and create a free account. Once you have an account and log in to Heroku, you will have access to a dashboard, where all your applications are listed.

Installing the Heroku CLI

Heroku provides a command-line tool for interacting with their service called Heroku CLI, available for Windows, Mac OS X and Linux. The documentation includes installation instructions for all the supported platforms. Go ahead and install it on your system if you plan on deploying the application to test the service.

The first thing you should do once the CLI is installed is login to your Heroku account:

$ heroku login

Heroku CLI will ask you to enter your email address and your account password. Your authenticated status will be remembered in subsequent commands.

Setting Up Git

The git tool is core to the deployment of applications to Heroku, so you must install it on your system if you don't have it yet. If you don't have a package available for your operating system, you can visit the git site to download an installer.

There are a lot of reasons why using git for your projects makes sense. If you plan to deploy to Heroku, you have one more, because to deploy to Heroku, your application must be in a git repository. If you are going to do a test deployment for Microblog, you can clone the application from GitHub:

$ git clone https://github.com/miguelgrinberg/microblog
$ cd microblog
$ git checkout v0.18

The git checkout command selects the specific commit that has the application at the point in its history that corresponds to this chapter.

If you prefer to work with your own code instead of mine, you can transform your own project into a git repository by running git init . on the top-level directory (note the period after init, which tells git that you want to create the repository in the current directory).

Creating a Heroku Application

To register a new application with Heroku, you use the apps:create command from the root directory of the application, passing the application name as the only argument:

$ heroku apps:create flask-microblog
Creating flask-microblog... done
http://flask-microblog.herokuapp.com/ | https://git.heroku.com/flask-microblog.git

Heroku requires that applications have a unique name. The name flask-microblog that I used above is not going to be available to you because I'm using it, so you will need to pick a different name for your deployment.

The output of this command will include the URL that Heroku assigned to the application, and also its git repository. Your local git repository will be configured with an extra remote, called heroku. You can verify that it exists with the git remote command:

$ git remote -v
heroku  https://git.heroku.com/flask-microblog.git (fetch)
heroku  https://git.heroku.com/flask-microblog.git (push)

Depending on how you created your git repository, the output of the above command could also include another remote called origin.

The Ephemeral File System

The Heroku platform is different to other deployment platforms in that it features an ephemeral file system that runs on a virtualized platform. What does that mean? It means that at any time, Heroku can reset the virtual server on which your server runs back to a clean state. You cannot assume that any data that you save to the file system will persist, and in fact, Heroku recycles servers very often.

Working under these conditions introduces some problems for my application, which uses a few files:

  • The default SQLite database engine writes data in a disk file
  • Logs for the application are also written to the file system
  • The compiled language translation repositories are also written to local files

The following sections will address these three areas.

Working with a Heroku Postgres Database

To address the first problem, I'm going to switch to a different database engine. In Chapter 17 you saw me use a MySQL database to add robustness to the Ubuntu deployment. Heroku has a database offering of its own, based on the Postgres database, so I'm going to switch to that to avoid the file-based SQLite.

Databases for Heroku applications are provisioned with the same Heroku CLI. In this case I'm going to create a database on the free tier:

$ heroku addons:add heroku-postgresql:hobby-dev
Creating heroku-postgresql:hobby-dev on flask-microblog... free
Database has been created and is available
 ! This database is empty. If upgrading, you can transfer
 ! data from another database with pg:copy
Created postgresql-parallel-56076 as DATABASE_URL
Use heroku addons:docs heroku-postgresql to view documentation

The URL for the newly created database is stored in a DATABASE_URL environment variable that will be available when the application runs. This is very convenient, because the application already looks for the database URL in that variable.

Logging to stdout

Heroku expects applications to log directly to stdout. Anything the application prints to the standard output is saved and returned when you use the heroku logs command. So I'm going to add a configuration variable that indicates if I need to log to stdout or to a file like I've been doing. Here is the change in the configuration:

config.py: Option to log to stdout.

class Config(object):
    # ...
    LOG_TO_STDOUT = os.environ.get('LOG_TO_STDOUT')

Then in the application factory function I can check this configuration to know how to configure the application's logger:

app/__init__.py: Log to stdout or file.

def create_app(config_class=Config):
    # ...
    if not app.debug and not app.testing:
        # ...

        if app.config['LOG_TO_STDOUT']:
            stream_handler = logging.StreamHandler()
            if not os.path.exists('logs'):
            file_handler = RotatingFileHandler('logs/microblog.log',
                                               maxBytes=10240, backupCount=10)
                '%(asctime)s %(levelname)s: %(message)s '
                '[in %(pathname)s:%(lineno)d]'))

        app.logger.info('Microblog startup')

    return app

So now I need to set the LOG_TO_STDOUT environment variable when the application runs in Heroku, but not in other configurations. The Heroku CLI makes this easy, as it provides an option to set environment variables to be used at runtime:

$ heroku config:set LOG_TO_STDOUT=1
Setting LOG_TO_STDOUT and restarting flask-microblog... done, v4

Compiled Translations

The third aspect of Microblog that relies on local files is the compiled language translation files. The more direct option to ensure those files never disappear from the ephemeral file system is to add the compiled language files to the git repository, so that they become part of the initial state of the application once it is deployed to Heroku.

A more elegant option, in my opinion, is to include the flask translate compile command in the start up command given to Heroku, so that any time the server is restarted those files are compiled again. I'm going to go with this option, since I know that my start up procedure is going to require more than one command anyway, since I also need to run the database migrations. So for now, I will set this problem aside, and will revisit it later when I write the Procfile.

Elasticsearch Hosting

Elasticsearch is one of the many services that can be added to a Heroku project, but unlike Postgres, this is not a service provided by Heroku, but by third parties that partner with Heroku to provide add-ons. At the time I'm writing this, there are three different providers of an integrated Elasticsearch service.

Before you configure Elasticsearch, be aware that Heroku requires your account to have a credit card on file before any third party add-on is installed, even if you stay within their free tiers. If you prefer not to provide your credit card to Heroku, then skip this section. You will still be able to deploy the application, but the search functionality is not going to work.

Out of the Elasticsearch options that are available as add-ons, I decided to try SearchBox, which comes with a free starter plan. To add SearchBox to your account, you have to run the following command while being logged in to Heroku:

$ heroku addons:create searchbox:starter

This command will deploy an Elasticsearch service and leave the connection URL for the service in a SEARCHBOX_URL environment variable associated with your application. Once more keep in mind that this command will fail unless you add your credit card to your Heroku account.

If you recall from Chapter 16, my application looks for the Elasticsearch connection URL in the ELASTICSEARCH_URL variable, so I need to add this variable and set it to the connection URL assigned by SearchBox:

$ heroku config:get SEARCHBOX_URL
$ heroku config:set ELASTICSEARCH_URL=<your-elasticsearch-url>

Here I first asked Heroku to print the value of SEARCHBOX_URL, and then I added a new environment variable with the name ELASTICSEARCH_URL set to that same value.

Updates to Requirements

Heroku expects the dependencies to be in the requirements.txt file, exactly like I defined it in Chapter 15. But for the application to run on Heroku I need to add two new dependencies to this file.

Heroku does not provide a web server of its own. Instead, it expects the application to start its own web server on the port number given in the environment variable $PORT. Since the Flask development web server is not robust enough to use for production, I'm going to use gunicorn again, the server recommended by Heroku for Python applications.

The application will also be connecting to a Postgres database, and for that SQLAlchemy requires the psycopg2 package to be installed.

Both gunicorn and psycopg2 need to be added to the requirements.txt file.

The Procfile

Heroku needs to know how to execute the application, and for that it uses a file named Procfile in the root directory of the application. The format of this file is simple, each line includes a process name, a colon, and then the command that starts the process. The most common type of application that runs on Heroku is a web application, and for this type of application the process name should be web. Below you can see a Procfile for Microblog:

Procfile: Heroku Procfile.

web: flask db upgrade; flask translate compile; gunicorn microblog:app

Here I defined the command to start the web application as three commands in sequence. First I run a database migration upgrade, then I compile the language translations, and finally I start the server.

Because the first two sub-commands are based on the flask command, I need to add the FLASK_APP environment variable:

$ heroku config:set FLASK_APP=microblog.py
Setting FLASK_APP and restarting flask-microblog... done, v4
FLASK_APP: microblog.py

The application also relies on other environment varialbes, such as those that configure the email server or the token for the live translations. Those need to be added with addition heroku config:set commands.

The gunicorn command is simpler than what I used for the Ubuntu deployment, because this server has a very good integration with the Heroku environment. For example, the $PORT environment variable is honored by default, and instead of using the -w option to set the number of workers, heroku recommends adding a variable called WEB_CONCURRENCY, which gunicorn uses when -w is not provided, giving you the flexibility to control the number of workers without having to modify the Procfile.

Deploying the Application

All the preparatory steps are complete, so now it is time to run the deployment. To upload the application to Heroku's servers for deployment, the git push command is used. This is similar to how you push changes in your local git repository to GitHub or other remote git server.

And now I have reached the most interesting part, where I push the application to our Heroku hosting account. This is actually pretty simple, I just have to use git to push the application to the master branch of the Heroku git repository. There are a couple of variations on how to do this, depending on how you created your git repository. If you are using my v0.18 code, then you need to create a branch based on this tag, and push it as the remote master branch, as follows:

$ git checkout -b deploy
$ git push heroku deploy:master

If instead, you are working with your own repository, then your code is already in a master branch, so you first need to make sure that your changes are committed:

$ git commit -a -m "heroku deployment changes"

And then you can run the following to start the deployment:

$ git push heroku master

Regardless of how you push the branch, you should see the following output from Heroku:

$ git push heroku deploy:master
Counting objects: 247, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (238/238), done.
Writing objects: 100% (247/247), 53.26 KiB | 3.80 MiB/s, done.
Total 247 (delta 136), reused 3 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote: -----> Python app detected
remote: -----> Installing python-3.6.2
remote: -----> Installing pip
remote: -----> Installing requirements with pip
remote: -----> Discovering process types
remote:        Procfile declares types -> web
remote: -----> Compressing...
remote:        Done: 57M
remote: -----> Launching...
remote:        Released v5
remote:        https://flask-microblog.herokuapp.com/ deployed to Heroku
remote: Verifying deploy... done.
To https://git.heroku.com/flask-microblog.git
 * [new branch]      deploy -> master

The label heroku that we used in the git push command is the remote that was automatically added by the Heroku CLI when the application was created. The deploy:master argument means that I'm pushing the code from the local repository referenced by the deploy branch to the master branch on the Heroku repository. When you work with your own projects, you will likely be pushing with the command git push heroku master, which pushes your local master branch. Because of the way this project is structured, I'm pushing a branch that is not master, but the destination branch on the Heroku side always needs to be master as that is the only branch that Heroku accepts for deployment.

And that is it, the application should now be deployed at the URL that you were given in the output of the command that created the application. In my case, the URL was https://flask-microblog.herokuapp.com, so that is what I need to type to access the application.

If you want to see the log entries for the running application, use the heroku logs command. This can be useful if for any reason the application fails to start. If there were any errors, those will be in the logs.

Deploying Application Updates

To deploy a new version of the application, you just need to run a new git push command with the new code. This will repeat the deployment process, take the old deployment offline, and then replace it with the new code. The commands in the Procfile will run again as part of the new deployment, so any new database migrations or translations will be updated during the process.


  • #76 Debashish Palit said 2019-08-11T10:26:21Z

    Hi Miguel, I tried out the changes you suggested. Both HTTP_X_FORWARDED_PROTO and wsgi.url_scheme have the value 'https'. It seems gunicorn sets the wsgi.url_scheme by checking HTTP_X_FORWARDED_PROTO field - I checked the gunicorn docs. So ProxyFix will perhaps not be needed here. I might mention that I have another (bottle) app running with the paste wsgi server on heroku. In this case, wsgi.url_scheme is 'http' when HTTP_X_FORWARDED_PROTO is 'https'. Thanks, Debashish

  • #77 Miguel Grinberg said 2019-08-11T20:43:33Z

    @Debashish: are you positive your gunicorn configuration does not have SSL enabled? I'm surprised wsgi.url_scheme is https if the request was received without encryption.

  • #78 Debashish Palit said 2019-08-12T00:44:49Z

    Hi Miguel, I have not done any special setup for gunicorn. It's the default setup that I am using with the Heroku free tier. I found this in the gunicorn docs about wsgi.url_scheme:

    {'X-FORWARDED-PROTOCOL': 'ssl', 'X-FORWARDED-PROTO': 'https', 'X-FORWARDED-SSL': 'on'} A dictionary containing headers and values that the front-end proxy uses to indicate HTTPS requests. These tell Gunicorn to set wsgi.url_scheme to https, so your application can tell that the request is secure.

    Maybe this explains why wsgi.url_sheme is https when the request is received without encryption. Thanks, Debashish

  • #79 Miguel Grinberg said 2019-08-12T20:50:36Z

    @Debashish: you are correct. It looks like this is a relatively new feature I was not aware of. It was added in 2018. So I guess now you need ProxyFix only if you need to get the client's IP address, because for the scheme gunicorn handles this on its own. Thanks!

  • #80 nathan said 2019-08-19T15:03:40Z

    Hi Miguel, I am trying to deploy the app, but the Elasticsearch/ searchbox on Heroku is giving me an 404 error of "No such index". The search was working locally, here is the traceback:

    2019-08-19T14:55:58.091938+00:00 app[web.1]: Exception on /search [GET] 2019-08-19T14:55:58.091941+00:00 app[web.1]: Traceback (most recent call last): 2019-08-19T14:55:58.091943+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app 2019-08-19T14:55:58.091945+00:00 app[web.1]: response = self.full_dispatch_request() 2019-08-19T14:55:58.091947+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request 2019-08-19T14:55:58.091949+00:00 app[web.1]: rv = self.handle_user_exception(e) 2019-08-19T14:55:58.091951+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception 2019-08-19T14:55:58.091953+00:00 app[web.1]: reraise(exc_type, exc_value, tb) 2019-08-19T14:55:58.091955+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise 2019-08-19T14:55:58.091957+00:00 app[web.1]: raise value 2019-08-19T14:55:58.091958+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request 2019-08-19T14:55:58.091960+00:00 app[web.1]: rv = self.dispatch_request() 2019-08-19T14:55:58.091962+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request 2019-08-19T14:55:58.091964+00:00 app[web.1]: return self.view_functionsrule.endpoint 2019-08-19T14:55:58.091966+00:00 app[web.1]: File "/app/app/main/routes.py", line 134, in search 2019-08-19T14:55:58.091968+00:00 app[web.1]: current_app.config["POSTS_PER_PAGE"]) 2019-08-19T14:55:58.091970+00:00 app[web.1]: File "/app/app/models.py", line 27, in search 2019-08-19T14:55:58.091977+00:00 app[web.1]: ids, total = query_index(cls.tablename, expression, page, per_page) 2019-08-19T14:55:58.091979+00:00 app[web.1]: File "/app/app/search.py", line 25, in query_index 2019-08-19T14:55:58.091981+00:00 app[web.1]: 'from': (page-1)per_page, 'size': per_page}) 2019-08-19T14:55:58.091983+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/elasticsearch/client/utils.py", line 76, in _wrapped 2019-08-19T14:55:58.091985+00:00 app[web.1]: return func(args, params=params, **kwargs) 2019-08-19T14:55:58.091986+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/elasticsearch/client/init.py", line 660, in search 2019-08-19T14:55:58.091988+00:00 app[web.1]: doc_type, '_search'), params=params, body=body) 2019-08-19T14:55:58.091990+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/elasticsearch/transport.py", line 318, in perform_request 2019-08-19T14:55:58.091992+00:00 app[web.1]: status, headers_response, data = connection.perform_request(method, url, params, body, headers=headers, ignore=ignore, timeout=timeout) 2019-08-19T14:55:58.091994+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/elasticsearch/connection/http_urllib3.py", line 186, in perform_request 2019-08-19T14:55:58.091996+00:00 app[web.1]: self._raise_error(response.status, raw_data) 2019-08-19T14:55:58.091998+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/elasticsearch/connection/base.py", line 125, in _raise_error 2019-08-19T14:55:58.092000+00:00 app[web.1]: raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info) 2019-08-19T14:55:58.092041+00:00 app[web.1]: elasticsearch.exceptions.NotFoundError: NotFoundError(404, 'index_not_found_exception', 'no such index')

  • #81 Miguel Grinberg said 2019-08-19T18:05:32Z

    @nathan: this is probable correct, the problem could be that data is not being saved when a new post is written. Have you checked if the insertion is working or not?

  • #82 Davide Scandella said 2019-10-10T00:16:43Z

    Hi Miguel, Thank you for the nice tutorial, it is of great help! I have a small project with a Raspberry pi, reading data from a PV inverter and saving it to sqlite every XX mins. I created a flask app that shows production charts and other plots thanks to bokeh module. Assuming that I migrate the db to postgresql, how can I deploy the app to Heroku, still being able to commit onto the database from the RPi, i.e. outside of the app? Thank you in advance. Davide

  • #83 Miguel Grinberg said 2019-10-10T10:03:15Z

    @Davide: What I would do is add an endpoint to the Flask app that accepts the data from the RPi and saves it to the database. This should be a POST request, and can accept the data in JSON format. I think this is the most convenient solution, because your Flask app is going to be configured to access the database already.

  • #84 Davide Scandella said 2019-10-11T23:57:52Z

    Yes, thank you Miguel, great idea. I didn't think about that! :)

  • #85 Tom said 2019-10-29T09:41:59Z

    Hi Miguel, Exellent course! But I'm stuck right now... When I try to deploy on Heroku, it doesn't start a process. This is because there is an error in the execution of the Procfile. I ran 'heruko local' and the output was:

    09:50:33 web.1 : Usage: flask db [OPTIONS] COMMAND [ARGS] . . . 09:50:33 web.1 : Error: No such command "upgrade;". [DONE] Killing all processes with signal SIGINT 09:59:33 web.1 Exited with exit code null

  • #86 Miguel Grinberg said 2019-10-30T12:04:33Z

    @Tom: did you check your Procfile? You must have an error there.

  • #87 Olivier Del said 2019-12-09T21:45:37Z

    Hi Miguel, Thank you for your course, it s great. I am currently struggling with deployement on heroku when I followed the steps. So I took all your code (v0.18). I run again flask migrate and I set config, both in flaskenv and directly in prompt with : heroku config:set SECRET_KEY= heroku config:set FLASK_APP=microblog.py heroku config:get SEARCHBOX_URL heroku config:set ELASTICSEARCH_URL= heroku config:set MAIL_SERVER=smtp.googlemail.com heroku config:set MAIL_PORT=587 heroku config:set MS_TRANSLATOR_KEY=my_key heroku config:set MAIL_USERNAME=@gmail.com heroku config:set MAIL_PASSWORD=*** heroku config:set MAIL_USE_TLS=1

    I got a first error, solved with doc_type='_doc' in : search.py Now I got this error : sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) relation "user" does not exist app[web.1]: LINE 2: FROM "user" [SQL: 'SELECT "user".id AS user_id, "user".username AS user_username, "user".email AS user_email, "user".password_hash AS user_password_hash, "user".about_me AS user_about_me, "user".last_seen AS user_last_seen \nFROM "user " \nWHERE "user".username = %(username_1)s \n LIMIT %(param_1)s'] [parameters: {'username_1': 'oli', 'param_1': 1}] I tried to do flask db migrate and upgrade localy again, then to add in procfile flask db init. But it failed and even if people have similar issues (even here in other chapters), I don't get the link with mine. Because it works well localy but it is KO on heroku when I try to register. And I don't see how debug remotly. If you an idea I would be grateful. Have a good day !

  • #88 Miguel Grinberg said 2019-12-11T10:45:23Z

    @Olivier: the error indicates that the user table does not exist on the Heroku Postgres database. Did you run the "flask db upgrade" command to run all the migrations on that database? The "init" command is only done when you initialize your migration repository, it does not apply to a second installation, where the repository already exists and is include in source control.

  • #89 Jakub said 2019-12-13T20:33:14Z

    Hey, amazing tutorial. I still managed to run into issue that Google fails to help me with.

    Everything seems to work fine locally, but upon deploying on heroku bootstrap (I'm guessing) seems to fail. It straight up looks ugly, hX looks like normal text, cards don't have borders they used to have locally and so on.

    I didn't (I think) touch any bootstrap related thing since I took your solution, that is there are 2 (3 with import) lines in init base.html extends bootstrap/base.html.

    What could've possibly gone wrong?

  • #90 Miguel Grinberg said 2019-12-14T07:49:37Z

    @Jakub: open the browser's debugger and look for errors in the console or in the network tab. That might give you an idea of what's wrong.

  • #91 Mario said 2019-12-18T17:52:09Z

    Hi Miguel. I stumbled upon your awesome tutorial and it's proven to be invaluable for a current project. I've followed most of your steps with a handful of modifications of my own. Everything has been going more or less smoothly until I got a database error from Postgres when entering a post into a field: "psycopg2.DataError: value too long for type character varying(140)" (my forms take in a relatively large amount of text). It looks like I'll need to change my Post column from a large String() to Text. What is the best way to do this? Would I have to nuke the database and rebuild it? I see some indications online that migrations would solve it, but I'm hesitant to mess too much with something I'm not entirely comfortable with yet.

    Thanks for your great tutorial!

  • #92 Miguel Grinberg said 2019-12-20T10:31:28Z

    @Mario: Yes, absolutely, you should create a database migration with this change, as that will preserve your data. The procedure is that same as when adding a new table or column, see Chapter 4 for the details. The only thing you need to keep in mind is that Alembic by default does not detect type changes in columns. See https://stackoverflow.com/a/52181159/904393 for how to tell it to do.

  • #93 Brian said 2020-01-09T01:55:35Z

    Hi Miguel,

    Great tutorial. I got the search working great locally but getting this exception after pushing to heroku: elasticsearch.exceptions.NotFoundError: NotFoundError(404, 'index_not_found_exception', 'no such index [post]', post, index_expression)

    Though i should say that I pushed to heroku long before starting the elasticsearch section of this tutorial and I have existing posts and users. Would that explain my error?

    Also, back in the search chapter, i deleted this line: app.elasticsearch.indices.delete('posts') .. I was assuming that changes made in the flask shell were not permanent, but this could possibly be affecting it.

    Any help is appreciated.

  • #94 Miguel Grinberg said 2020-01-09T07:38:00Z

    @Brian: the elasticsearch index is separate from the database, it is updated in parallel to it every time you make changes. I suspect your problem is that your database has content that was never synced to elasticsearch. Try running the reindex() function, that should update ES with all the posts that are in your database.

  • #95 apk14 said 2020-01-27T06:42:58Z

    Hello Miguel. I have deployed the application on heroku and it is running very well. There is just one issue, Some users see a 'CSRF token did not match' error when they try to register every time. Why could it mean? I know that CSRF tokens are used to protect the users from cross site request forgery and I thought that maybe flask implements it by default on all forms as no other user faced that issue. Can you explain why is that error occuring?

  • #96 Miguel Grinberg said 2020-01-27T10:24:07Z

    @apk14: Any chance these clients have cookies disabled?

  • #97 apk14 said 2020-02-01T17:03:45Z

    Yes that might be the issue, however, I haven't been able to be sure about it yet. There is another issue that the email field gives error "invalid email address" to some user who gave the email as Testuser@gmail.com When i tried the same from my system it got accepted. Any idea why such an error would be raised?

  • #98 Miguel Grinberg said 2020-02-02T12:15:24Z

    @apk14: probably the user did not type the email as they told you. They may have added a space somewhere or some other thing that made the email invalid. You may want to add logging to your application if you need to track down strange behaviors like this one.

  • #99 Roman Postnikov said 2020-03-02T10:30:19Z

    Hi Miguel, thanks for the tutorial.

    During pushing to heroku I get the message "ERROR: Could not find a version that satisfies the requirement anaconda-client==1.7.2"

    Do you know what can be the issue and how to solve this one? Thanks!

  • #100 Miguel Grinberg said 2020-03-02T11:27:04Z

    @Roman: the package anaconda-client does not have a version 1.7.2, your requirements file needs to be fixed to define a valid version for this package.

Leave a Comment