I like that you show every file involved and where it is and how you're doing it. This process is all about connecting different things and so many of the tutorials show only one piece so you don't know what the other pieces are supposed to look like in their particular example. Showing the many different files is NECESSARY thank you!
Thank you. It is ridiculous what we need to do in order to solve such a simple task. Shame that in all those years of internet they never came to a better and simpler solution.
I think it is obvious that you do not have knowledge on this topic. Nothibg is more complicated than it should be. It is a quite simple task. A lot of people confuse the "complex" with "time consuming". This process is just time consuming although gives an opportunity to fully customize your web app and server.
@@HTWwpzIuqaObMt By lowering the "complexity" you can lower the "time consumption". what Tujark meant is that this process could've been abstracted more because not everyone needs the customization.
@@HTWwpzIuqaObMt I have been analyzing web development for 10 years, and development in general. Even the simplest things cannot make it work out of the box. This is ridiculous. Millions of developers correct configs like children at school correct mistakes in a notebook. And yes, this tutorial does not run on the current ubuntu and apache
This was awesome! I just built my very first flask app (actually my first web page) and wanted to try to deploy what I have next week for testing. Even without seeing the file structure of the server, I understood what you were explaining so I'm pretty confident. Thank you!
Great vid. Thanks for including the troubleshoots. This is just what I needed for deploying my first flask app to a container. it’s awesome that it’s running on Apache because that makes the letsencrypt certificate renewals that much easier as well!
@@LukePeters I actually don't have any goals in mind. I just playing with my new toy and using it to learn cool and interesting stuff. I think it's neat that I can communicate with it over the internet no matter where I am.
@@julienweems6166 Oh okay cool. Playing around with new tech toys is the best 😃 I still don't have a Raspberry Pi despite being curious about them for years. Might have to change that now...
👍The Perfect Tutorial! 👍 I am already comfortable with Apache and virtual domains and just needed a quick run through for hosting Python apps. The only thing that would make it better would be having a guthub repo with your project files. Excellent video, thank you.
Hi Luke, I cannot find the activate_this.py script in my Python virtual environment. I do find the activate under the corresponding bin directory. Any ideas? Thanks David
Hey luke. Thanks for the video. How did you chnage your terminal color? The colors looks very pleasing! Are you using iterm and omz? What is the theme? 😅
Hi Luke, I’m on VPS and I have pointed 000-default.conf and default-ssl.conf to point to my folder like in your video. Apache only serves my files, your example program and Apache doesn’t enable swgi file. Getting errors
Hello, great video! The only thing is that I always get an error and in my error.log file it says permission denied for the activate_this.py file path. Do you know how to solve this?
Hey, this probably means that Apache doesn’t have permission to access the activate_this.py file. I would try changing the group that file is in to your Apache user group - and make sure the parent directories have the same group, otherwise Apache won’t be able to get into the folder where that file lives. Example: sudo chgrp -R www-data /var/www/your_app Modify this to match the path to your app’s root directory.
Hi Adrianñ, yes, this approach will also work for a Flask app that uses SQLAlchemy. But this video just covers the Flask setup steps, there will be additional database setup/configuration steps depending on the database you're using. Start by double-checking that the database is running, make sure your database connection config is correct in the Flask code, and check your server error logs (for Apache and your database).
Thanks for the video - got my app up and running on apache in no time! I wonder if I could get your help on something? My app uses the flask function send_from_directory to let the user download a spreadsheet when they click a button. Works fine when I test it locally but I get an permission error (Error 13) on the live server. Permissions on the file are set to 755 and owner is www-data. Not sure what else I need to make it accessible?
Hey! Glad the tutorial was helpful. Hmm, that's interesting... What user/user group is WSGI/Flask running as? Perhaps the parent directory doesn't have the appropriate permissions on it?
@@LukePeters Thanks for the reply. Flask is running as www-data as far as I can tell (i.e. when I change read permissions on other files I'm using it opens them up to flask as expected). Is there an explicit way to check or specify the user Flask runs as though? Pretty sure it's not the parent directory. www-data is the owner and has write permissions for the whole path. The owner of all other files I'm working with is root.
I have centos 7 os there is no ditectory as var/www for apache but httpd service is enabled. Also there is no site enable command to enable it . Please guide.
Hi, using old version of linux mint, but for every step I take something goes wrong... why would this be happening? For instance I get pkg_resources cannot be imported, when I've written "pip install setuptools" 100 times
Hi, very good tutorial. Everything running fine. I notice that if i change the home.html the content change only of i refresh apache. can you provide a solution to that ? I have already add WSGIScriptReloading On on virtual site but it didnt work. Thanks
Hey, great video. Gonna be super helpful! I´ve been using pyenv to manage virtual envs, is it possible to make this work with pyenv or is pipenv the only way? If possible, could you explain how? Because there is no activate.this file, only a .python_version file that lies in my flask_app folder.
Hi Luke, I am getting Forbidden You don't have permission to access this resource. Error looks like- Tue Apr 26 06:17:49.494203 2022] [autoindex:error] [pid 313:tid 140507386562304] [client 125.16.206.250:64225] AH01276: Cannot serve directory /var/www/smap/docgen/: No matching DirectoryIndex (index.html,index.htm,index.shtml) found, and server-generated directory index forbidden by Options directive. Thanks in advance
Hey Parth, have you found an answer to this problem? If so, would you mind sharing here for others? I've never run into this particular error while deploying Flask apps on Apache, but I've just done a bit of Google searching about it and I'm really not sure what it could be without looking at your app and server config.
Thank you for the guide. I've followed it meticulously and the server will not serve WSGI flask page, instead, continually serves the default apache index.html. Any ideas why?
Figured it out, deployed this on amazon EC2 ubuntu host, accessing from home. Worked when ServerName in the appname.conf was configured to the "Public IPv4 DNS" of the ec2 instance. Now to figure out the permissions to the virtualenv issue I see below and am experiencing right now.
figured out the permissions issue, Actually @jars99 did below (Thank you, Thank you, Thank you!) for some reason, on my EC2 ubuntu instance, Apache doesn't like finding your virtual environment files in directories other than /usr (thankfully I followed @jars99 suggestion and it worked first time. i.e., other directories might work, but I wasn't doing any more experimenting to find out) /usr/local/venvs didn't exist at first cd /usr/local sudo mkdir venvs cd venvs sudo cp -R ./ I didn't even change the permissions (left them as root) (@jars99 said he changed them. Mileage might vary.) Next modify your ".wsgi" file to use the new venv. (line 4 in Luke's example, around minute 5:00) activate_this = '/usr/local/venvs//bin/activate_this.py' { example: activate_this = '/usr/local/venvs/flaskapp-m09E3mlH/bin/activate_this.py' } Remember to keep your 'Servername' field in /etc/apache2/sites-available/.conf updated to your AWS instance "Public IPv4 DNS" (go to your AWS console to find it) { example: nano /etc/apache2/sites-available/flask-app.conf ServerName ec2-28-198-124-113.us-east-1.compute.amazonaws.com } and, on that instance, in AWS console: don't forget to update your "Security: Inbound rules" to include a port 80 ingress from your IP (whatsmyip.com or All) access your app by using the AWS public DNS name in your browser: example from above: ec2-28-198-124-113.us-east-1.compute.amazonaws.com (no httpS !!! No S! you didn't configure TLS/SSL, that's 443 and you'll have to find another tutorial for that)
Hi Robert, the static folder is a good place to store CSS files, JavaScript files, images, etc. You can name this folder anything you want. You don’t need a static folder to deploy a Flask app. But if your app has static assets (unchanging files), you’ll need a place to put them.
Ok thanks. Last question, I got this to work but the / (root site) is still showing Apache2 Ubuntu Default page. Any idea how I can get rid of the default page?
@@robertagilar3920 No problem! There's probably still a default VirtualHost config file pointing to "/var/www/html" where there's an "index.html" file created by Apache. Disable that VirtualHost config file - probably something like "sudo a2dissite 000-default.conf", but check what's on your server under /etc/apache2/sites-enabled".
Luke Peters, i want ask something, i we change the port in file basic-flask-app.conf (for example 4000) then we test in browser with ip:4000? is that correct?
Hey Jundi, yes, that is correct 👍🏻 But keep in mind that Apache might not have port 4000 open (or might not be listening on it). It usually has port 80 (http) and 443 (https) open, but you may have to tell Apache to open/listen to port 4000 for it to work. This guide should help: ubiq.co/tech-blog/how-to-change-port-number-in-apache-in-ubuntu/ And if you have a firewall (UFW) running on Apache, you may need to allow your new port: sudo ufw allow 4000
mod_wsgi works with Apache only (not Nginx) and runs on both Linux and Windows. Gunicorn works with Apache and Nginx but doesn't run on Windows. I haven't used Gunicorn so I don't have real-world experience to compare them to each other, but it seems Gunicorn may be easier to setup and in some scenarios might be more performant. I would say try them both and see which you like better.
@@LukePeters thanks much for the response! I have since learned that for prod you need to do some good setup steps with Nginx too, so neither is really completely non-trivial--the getting started with gunicorn makes it feel that way.
hi, nice tutorial very detailed, but i have a strange issue on the wsgi file, i can't understand what is wrong apparently the istrucions "with open(activate_this) as file_: exec(file_.read(), dict(__file__=activate_this))" generate an error and i tried many solutions but non of them works
@@LukePeters oh yeah sorry UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 27524: ordinal not in range(128) mod_wsgi (pid=7101): Target WSGI script '/var/www/HomeWebServer/HomeWebServer.wsgi' cannot be loaded as Python module. mod_wsgi (pid=7101): Exception occurred processing WSGI script '/var/www/HomeWebServer/HomeWebServer.wsgi'. Traceback (most recent call last): File "/var/www/HomeWebServer/HomeWebServer.wsgi", line 8, in ù exec(file_.read(), dict(__file__=activate_this)) File "/usr/lib/python3.5/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 27524: ordinal not in range(128) this is what i get ty
@@filippo1984 That's more like it! This error means the app is trying to process some character that isn't Unicode-friendly. See where it mentions "0xc2"? That's binary code for this character: Â
@@filippo1984 Do you have a database? Look at the data inside your database. Are you uploading/processing files with the app? Look in those files. If you don't have either, then it's probably just an accidental character in your code. But do some research on the subject. I can't help you find it in your code, but you can read up about the error and diagnose the problem. Take it step by step. Disable parts of the app until it works, then reenable one by one until it breaks, then you'll know which part contains the problem.
Definitely use some kind of virtual environment. It's not a good idea to install Python dependencies (i.e. Flask) on your computer globally with pip. You want to make sure you're inside a virtual environment before installing dependencies. If you don't want to use Pipenv to manage your virtual environment you can use Virtualenv instead: 1. Install Virtualenv on your computer: pip install virtualenv 2. Create a virtual environment: virtualenv venv 3. Then activate the virtual environment: source venv/bin/activate 3.1: If you're on Windows: venv\Scripts\activate 4. Then install dependencies with Pip: pip install flask
@@LukePeters Thank you for your advice, I have used virtualenv. Now I have deployed my web application on Apache Web server, but now accessing the URL it is showing "Forbidden You don't have permission to access this resource", I have applied chmod 777 to all files. Then also the same error is coming. Can you help me with this?
@@parthpandey4631 Hi Parth, it's going to be very slow trying to guess where the problem is - check your error logs! They should tell you more information about WHICH resource is lacking the proper permissions. The error log for the Flask app is configured in the "basic-flask-app.conf" file (@5:49 in this video): /var/www/basic-flask-app/logs/error.log You can also check your default Apache error log, which should live here: /var/log/apache2/error.log If the server is giving you a big server error when you visit the URL, then the server is logging more details about the error somewhere. Probably in one of these two files.
Thanks for the video, I was able to deploy the app on the apache server, however with apache I cannot connect to SQL Server, although the configuration is correct. But if I launch the app from the cmd everything works, does anyone know why?
Check the error logs! There's a specific error message or error code being stored somewhere, which is a great place to start debugging. Too many possible reasons for a failure to connect.
@@LukePeters Same error for me, apparently we should do something to include for example sqlalchemy, it simply does not commit or query anything from the db file
@@adrianrs79 Did you check your app's error logs? What about the general Apache error logs? You can also implement your own logging within Flask. Follow these steps: snipsave.com/user/lukepeters/snippet/9a7HzD5gyzYxJybWru/ Then you will hopefully see some kind of database errors in the "debug.log" file after trying to load/use your app again.
I was able to install everything without any errors. I am facing some issue after starting the apache server and trying to access the server from chrome. Am getting two errors in the error log: 1] PermissionError: [Errno 13] Permission denied: '/root/.local/share/virtualenvs/OnlineLearner-uZdfk3kh/bin/activate_this.py' 2] Target WSGI script '/var/www/OnlineLearner/app.wsgi' cannot be loaded as Python module. Please help me out Luke. Thanks in advance!!
Hey Sudesh! Can you check whether Apache has permission to read/write the virtualenvs/ directory? On Ubuntu/Debian servers, Apache runs as the user "www-data" under the group "www-data" by default. In this case, you might do something like this: sudo chown -R www-data /root/.local/share/virtualenvs Or you could just change the directory's group to the same as Apache: sudo chgrp -R www-data /root/.local/share/virtualenvs Or you could run Apache under your own username (or whichever username CURRENTLY owns the virtualenvs/ directory). Check out this article to learn how to change which user/group Apache runs as: www.simplified.guide/apache/change-user-and-group And to find out which user CURRENTLY owns the virtualenvs/ directory do this: ls -ld /root/.local/share/virtualenvs I know that's a lot, but I hope it helps!
Thank you! The very first thing you need to do is check the Apache error logs. They should contain more information about what isn’t working. In this video in the .conf file we specified a custom error log path. Check that file for more information. You can also check the default Apache logs for more information: /var/log/apache2/error.log Without more information from an error log and without seeing your code it’s impossible to know why it’s not working.
@@LukePeters that's a problem, the error log shows nothing, my api runs fine in development mode and runs in production, but now I don't know if WSGI blocks input data or something like that thanks for answer greetings
Hey Luke, thanks for the great tutorial! I've been able to deploy my website :)) I'm struggling with the error: app called on a post request cannot connect to X server. It runs perfectly on pycharm, but throws this error on the deployed version. I have changed the wsgi user,, exported the app to $PATH but no success. I read every related post on stackoverflow... Would you give me a hint on that? Thanks
Hey Caio! I'm glad this tutorial was helpful! I did a little research on your error message. Is your Python app doing anything that requires a computer screen/display? Like taking a screenshot, or something else? In Linux, "X" is an application that manages graphics displays and input devices (like mice and keyboards). If your app utilizes the graphics card/display in some way, you may need to configure it to run in some kind of "headless" mode on the production server.
@@LukePeters Thanks for checking up on that. Yes, the flask app provides a web interface for a system that analyzes biomedical images. With user input, the flask app calls another app that pre-processes, infers (DL) and post-processes the uploaded raw image. This second app needs access to the display system (X-server). I know that might raise security issues, but that is the best way I have so far. I'm adding other security layers to limit the risks. The way I sorted that out was adding the line "os.environ["DISPLAY"] = ":1"" to the wsgi file (my $DISPLAY is :1) and it worked great. I'm now working on a dockerized xvfb solution to that, which I guess can reduce the risk a little more. Great channel, thanks again!
@@LukePeters Hay Luke I was wondering if you have found the answer to this question. I seem to be having the same issue and not sure why. The issue seems to be that open can not access the virtual environment activate_this.py file. Thanks and amazing video :)
@@warhawk3895 Hey! I can't help without a specific error message. There are many possible causes, many of them personal environment configuration issues which can be different for everyone.
@@LukePeters #!/usr/bin/python3 import sys import logging logging.basicConfig(stream=sys.stderr) sys.path.insert(0,"/var/www/cwh/" from cwh import app as application application.secret_key = 'Add-secret' i used this code in wsgi file
@@fahadshaikh9715 You don’t need to use a virtual environment if you a don’t want to. And root user isn’t an amazing idea for security, but it will totally work.
Sorry to hear that! I can't help with such little information, though 😅 Look at your APACHE ERROR LOGS! There's a clue somewhere. It's not just silently failing.
I am trying to run a Flask app on my raspberry with apache. Because this app sometimes needs GPIO-access, I can't run it without sudo. How can I tell apache to sudo run it? Or is there a better way? I also run into some problems when accessing the machine with its hostname instead of the IP. I then get the "Apache2 Debian Default Page" - unless I change line 4 in the .conf file. With WSGIScriptAlias /{path} /var/www/basic-flask-app/app.wsgi the error doesn't occurs. But then I have to call {hostname}.local/{path} instead of just {hostname}.local Do you have any idea how to solve this? I am working with a Raspberry Pi Zero as I mentioned above Thanks for the nice tutorial though!
"Cannot access directory '/var/www/html/logs/' for error log of vhost defined at /etc/apache2/sites-enabled/basic-flask-app.conf:1" I got this king for error while configtest Bro can you give a solution ???
It looks like Apache cannot access that directory. If the directory exists, it's probably a permissions error. Find out what user/group Apache runs as by looking at the /etc/apache2/envvars file. They're listed in there as APACHE_RUN_USER and APACHE_RUN_GROUP. Then make sure /var/www/html/logs is owned by the same user or group. If the user is 'www-data', do this: 'sudo chown www-data /var/www/html/logs -R'
👋🏻 Hey! Do you like Python? Web app development? Automation?! Let me know what topics you'd like to see me cover next! 😃
I like that you show every file involved and where it is and how you're doing it. This process is all about connecting different things and so many of the tutorials show only one piece so you don't know what the other pieces are supposed to look like in their particular example. Showing the many different files is NECESSARY thank you!
Thanks for the feedback! Nice to hear this approach was helpful :)
Thank you. It is ridiculous what we need to do in order to solve such a simple task. Shame that in all those years of internet they never came to a better and simpler solution.
I think it is obvious that you do not have knowledge on this topic. Nothibg is more complicated than it should be. It is a quite simple task. A lot of people confuse the "complex" with "time consuming". This process is just time consuming although gives an opportunity to fully customize your web app and server.
@@HTWwpzIuqaObMt By lowering the "complexity" you can lower the "time consumption". what Tujark meant is that this process could've been abstracted more because not everyone needs the customization.
@@HTWwpzIuqaObMt I have been analyzing web development for 10 years, and development in general.
Even the simplest things cannot make it work out of the box. This is ridiculous. Millions of developers correct configs like children at school correct mistakes in a notebook.
And yes, this tutorial does not run on the current ubuntu and apache
This was awesome! I just built my very first flask app (actually my first web page) and wanted to try to deploy what I have next week for testing. Even without seeing the file structure of the server, I understood what you were explaining so I'm pretty confident. Thank you!
I was trying to implement an API on my VPS and you helped me in 11:20 minutes more than any other source of information in 8 days of trying.
Great vid. Thanks for including the troubleshoots. This is just what I needed for deploying my first flask app to a container. it’s awesome that it’s running on Apache because that makes the letsencrypt certificate renewals that much easier as well!
Thx !!! i've been trying for a long time to deploy my flask app into digitalocean ubuntu server, only after use your config code (10:22) it worked.
Super happy to hear that! The first time I tried to deploy a Flask app was very frustrating. Glad this helped.
Thanks for the great tutorial! I know literally nothing about linux or apache and I still got it to work on my raspberry pi thanks to you
Hey that's awesome! Glad to hear this was helpful :) What does your app do that you want to run it on a Raspberry Pi?
@@LukePeters I actually don't have any goals in mind. I just playing with my new toy and using it to learn cool and interesting stuff. I think it's neat that I can communicate with it over the internet no matter where I am.
@@julienweems6166 Oh okay cool. Playing around with new tech toys is the best 😃 I still don't have a Raspberry Pi despite being curious about them for years. Might have to change that now...
Thank you very much for sharing this knowledge with us! I was very helpful!
you are like a god to me
i appreciate your hardwork alot🤧🤧
stay posted like these videos💖💖
Haha, well thank you! I appreciate you taking the time to let me know :)
Hello, thank you for this video, you saved me because I couldn't upload a server with my python flaskafter watching your tutorial.
Hi Luke that was an outstanding Tutorial!
Hi Patrick, thank you! I appreciate the comment :)
First ever time I thumbs up'd a vid.. outstanding tutorial, very detailed!
Thanks! Glad it was helpful!
Thank you, this video helped fixing an error in my configuration!
Glad to hear it!
👍The Perfect Tutorial! 👍 I am already comfortable with Apache and virtual domains and just needed a quick run through for hosting Python apps. The only thing that would make it better would be having a guthub repo with your project files. Excellent video, thank you.
Glad this was helpful!
The first useful tutorial at all for this usecase! Thy.
Nice! Thanks for dropping a comment 🤙🏻
Hi Luke,
I cannot find the activate_this.py script in my Python virtual environment. I do find the activate under the corresponding bin directory. Any ideas? Thanks
David
same problem> Din you find the solution?
same here, any ideas?
Got it working thanks!
Hey luke. Thanks for the video.
How did you chnage your terminal color? The colors looks very pleasing! Are you using iterm and omz? What is the theme? 😅
Thank you so much, you helped me a lot with your video! :)
Glad to hear that :) Thanks for letting me know!
You are awesome! It finally worked!
Awesome! Glad to hear that 😃
Hi Luke, I’m on VPS and I have pointed 000-default.conf and default-ssl.conf to point to my folder like in your video. Apache only serves my files, your example program and Apache doesn’t enable swgi file. Getting errors
Hello, great video! The only thing is that I always get an error and in my error.log file it says permission denied for the activate_this.py file path. Do you know how to solve this?
getting same error for permission denied, is there any solutions? Have tried to set the directory owner to www-data but no work
Hey, this probably means that Apache doesn’t have permission to access the activate_this.py file.
I would try changing the group that file is in to your Apache user group - and make sure the parent directories have the same group, otherwise Apache won’t be able to get into the folder where that file lives.
Example: sudo chgrp -R www-data /var/www/your_app
Modify this to match the path to your app’s root directory.
Hey Xiaoran, see my comment to Msa720 here. You may need to change the user group for the app’s root directory.
@@LukePeters Thanks for the answer, but how can I do that?
I included the sample code in my comment above.
what about if you have sqlalchemy, the way you illustrated the example can be applied to do so? thanks
Hi Adrianñ, yes, this approach will also work for a Flask app that uses SQLAlchemy. But this video just covers the Flask setup steps, there will be additional database setup/configuration steps depending on the database you're using. Start by double-checking that the database is running, make sure your database connection config is correct in the Flask code, and check your server error logs (for Apache and your database).
I almost wrote a comment "I love you for this incredible tutorial" but that would have been inappropriate...
Anyway, REALLY THANKS 🙏🏼 😀
Haha, either way I appreciate you taking the time to leave a comment 🙂
Thanks for the video - got my app up and running on apache in no time!
I wonder if I could get your help on something? My app uses the flask function send_from_directory to let the user download a spreadsheet when they click a button. Works fine when I test it locally but I get an permission error (Error 13) on the live server. Permissions on the file are set to 755 and owner is www-data. Not sure what else I need to make it accessible?
Hey! Glad the tutorial was helpful. Hmm, that's interesting... What user/user group is WSGI/Flask running as? Perhaps the parent directory doesn't have the appropriate permissions on it?
@@LukePeters Thanks for the reply. Flask is running as www-data as far as I can tell (i.e. when I change read permissions on other files I'm using it opens them up to flask as expected). Is there an explicit way to check or specify the user Flask runs as though?
Pretty sure it's not the parent directory. www-data is the owner and has write permissions for the whole path. The owner of all other files I'm working with is root.
I am having the same issue.
@@jasoncasey654 Unfortunately I never solved it for myself - I ended up leaving out the "download a spreadsheet" feature from my website :/
Yea, I just abandoned the use of the virtual environment. I used the global install of python instead and it works great
I have centos 7 os there is no ditectory as var/www for apache but httpd service is enabled. Also there is no site enable command to enable it . Please guide.
Thank u so much for the video. :)
You're welcome 🙂
Hi, using old version of linux mint, but for every step I take something goes wrong... why would this be happening? For instance I get pkg_resources cannot be imported, when I've written "pip install setuptools" 100 times
How to deploy multiple flask app on single server?
Hi, very good tutorial. Everything running fine.
I notice that if i change the home.html the content change only of i refresh apache.
can you provide a solution to that ?
I have already add
WSGIScriptReloading On
on virtual site but it didnt work.
Thanks
Hi. Thank you for the video. I'm not sure about the role of flask. So, if I have a html page, couldn't just use apache as a server for this page?
Hi João, the point of the video is to demonstrate how to deploy a Flask application on Apache. The example Flask app here is VERY basic on purpose.
Hey, great video. Gonna be super helpful! I´ve been using pyenv to manage virtual envs, is it possible to make this work with pyenv or is pipenv the only way? If possible, could you explain how? Because there is no activate.this file, only a .python_version file that lies in my flask_app folder.
Hey Trombasso, thanks! I've never used Pyenv myself, but this article seems like it might be helpful: linuxtut.com/en/84f073c463fd1b809521/
Hi Luke, I am getting Forbidden You don't have permission to access this resource. Error looks like-
Tue Apr 26 06:17:49.494203 2022] [autoindex:error] [pid 313:tid 140507386562304] [client 125.16.206.250:64225] AH01276: Cannot serve directory /var/www/smap/docgen/: No matching DirectoryIndex (index.html,index.htm,index.shtml) found, and server-generated directory index forbidden by Options directive. Thanks in advance
Hey Parth, have you found an answer to this problem? If so, would you mind sharing here for others?
I've never run into this particular error while deploying Flask apps on Apache, but I've just done a bit of Google searching about it and I'm really not sure what it could be without looking at your app and server config.
Worked, thank you :)
Cool :)
Thank you for the guide. I've followed it meticulously and the server will not serve WSGI flask page, instead, continually serves the default apache index.html. Any ideas why?
Figured it out, deployed this on amazon EC2 ubuntu host, accessing from home. Worked when ServerName in the appname.conf was configured to the "Public IPv4 DNS" of the ec2 instance. Now to figure out the permissions to the virtualenv issue I see below and am experiencing right now.
figured out the permissions issue, Actually @jars99 did below (Thank you, Thank you, Thank you!)
for some reason, on my EC2 ubuntu instance, Apache doesn't like finding your virtual environment files in directories other than /usr (thankfully I followed @jars99 suggestion and it worked first time. i.e., other directories might work, but I wasn't doing any more experimenting to find out)
/usr/local/venvs didn't exist at first
cd /usr/local
sudo mkdir venvs
cd venvs
sudo cp -R ./
I didn't even change the permissions (left them as root) (@jars99 said he changed them. Mileage might vary.)
Next modify your ".wsgi" file to use the new venv. (line 4 in Luke's example, around minute 5:00)
activate_this = '/usr/local/venvs//bin/activate_this.py'
{ example: activate_this = '/usr/local/venvs/flaskapp-m09E3mlH/bin/activate_this.py' }
Remember to keep your 'Servername' field in /etc/apache2/sites-available/.conf updated to your AWS instance "Public IPv4 DNS" (go to your AWS console to find it)
{ example: nano /etc/apache2/sites-available/flask-app.conf
ServerName ec2-28-198-124-113.us-east-1.compute.amazonaws.com
}
and, on that instance, in AWS console: don't forget to update your "Security: Inbound rules" to include a port 80 ingress from your IP (whatsmyip.com or All)
access your app by using the AWS public DNS name in your browser: example from above: ec2-28-198-124-113.us-east-1.compute.amazonaws.com (no httpS !!! No S! you didn't configure TLS/SSL, that's 443 and you'll have to find another tutorial for that)
Hi @Luke Peters,
New in to flask/apache/webdevelopment, what is this static folder for? Do I need it for my deploy of flask app?
Hi Robert, the static folder is a good place to store CSS files, JavaScript files, images, etc. You can name this folder anything you want.
You don’t need a static folder to deploy a Flask app. But if your app has static assets (unchanging files), you’ll need a place to put them.
Ok thanks. Last question, I got this to work but the / (root site) is still showing Apache2 Ubuntu Default page. Any idea how I can get rid of the default page?
@@robertagilar3920 No problem! There's probably still a default VirtualHost config file pointing to "/var/www/html" where there's an "index.html" file created by Apache. Disable that VirtualHost config file - probably something like "sudo a2dissite 000-default.conf", but check what's on your server under /etc/apache2/sites-enabled".
Luke Peters, i want ask something, i we change the port in file basic-flask-app.conf (for example 4000) then we test in browser with ip:4000? is that correct?
Hey Jundi, yes, that is correct 👍🏻 But keep in mind that Apache might not have port 4000 open (or might not be listening on it). It usually has port 80 (http) and 443 (https) open, but you may have to tell Apache to open/listen to port 4000 for it to work.
This guide should help: ubiq.co/tech-blog/how-to-change-port-number-in-apache-in-ubuntu/
And if you have a firewall (UFW) running on Apache, you may need to allow your new port: sudo ufw allow 4000
All right thank you!
Thanks for the video--why would I do this rather than use gunicorn?
mod_wsgi works with Apache only (not Nginx) and runs on both Linux and Windows.
Gunicorn works with Apache and Nginx but doesn't run on Windows.
I haven't used Gunicorn so I don't have real-world experience to compare them to each other, but it seems Gunicorn may be easier to setup and in some scenarios might be more performant. I would say try them both and see which you like better.
@@LukePeters thanks much for the response! I have since learned that for prod you need to do some good setup steps with Nginx too, so neither is really completely non-trivial--the getting started with gunicorn makes it feel that way.
Is it compulsory to make virtual env can we do same thing as root user?
hi, nice tutorial very detailed, but i have a strange issue on the wsgi file, i can't understand what is wrong apparently the istrucions "with open(activate_this) as file_:
exec(file_.read(), dict(__file__=activate_this))" generate an error and i tried many solutions but non of them works
Hey Filippo, what error do they generate? That's the most important piece of information for debugging! :)
@@LukePeters oh yeah sorry
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 27524: ordinal not in range(128)
mod_wsgi (pid=7101): Target WSGI script '/var/www/HomeWebServer/HomeWebServer.wsgi' cannot be loaded as Python module.
mod_wsgi (pid=7101): Exception occurred processing WSGI script '/var/www/HomeWebServer/HomeWebServer.wsgi'.
Traceback (most recent call last):
File "/var/www/HomeWebServer/HomeWebServer.wsgi", line 8, in
ù exec(file_.read(), dict(__file__=activate_this))
File "/usr/lib/python3.5/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 27524: ordinal not in range(128)
this is what i get ty
@@filippo1984 That's more like it! This error means the app is trying to process some character that isn't Unicode-friendly. See where it mentions "0xc2"? That's binary code for this character: Â
@@LukePeters thank you i will check and report to you the result, but how can i find it if is on the database or some others file?
@@filippo1984 Do you have a database? Look at the data inside your database. Are you uploading/processing files with the app? Look in those files. If you don't have either, then it's probably just an accidental character in your code. But do some research on the subject. I can't help you find it in your code, but you can read up about the error and diagnose the problem. Take it step by step. Disable parts of the app until it works, then reenable one by one until it breaks, then you'll know which part contains the problem.
I’m havin this error message: AssertionError: You must use exec(open(this_file).read(), {'__file__': this_file}))
You know what that can be?
I am not able to install pyvenv so I have used another way to install dependencies using pip install req.txt rather than using Pipfile.
Definitely use some kind of virtual environment. It's not a good idea to install Python dependencies (i.e. Flask) on your computer globally with pip. You want to make sure you're inside a virtual environment before installing dependencies.
If you don't want to use Pipenv to manage your virtual environment you can use Virtualenv instead:
1. Install Virtualenv on your computer: pip install virtualenv
2. Create a virtual environment: virtualenv venv
3. Then activate the virtual environment: source venv/bin/activate
3.1: If you're on Windows: venv\Scripts\activate
4. Then install dependencies with Pip: pip install flask
@@LukePeters Thank you for your advice, I have used virtualenv.
Now I have deployed my web application on Apache Web server, but now accessing the URL it is showing "Forbidden You don't have permission to access this resource", I have applied chmod 777 to all files. Then also the same error is coming. Can you help me with this?
@@parthpandey4631 Hi Parth, it's going to be very slow trying to guess where the problem is - check your error logs! They should tell you more information about WHICH resource is lacking the proper permissions.
The error log for the Flask app is configured in the "basic-flask-app.conf" file (@5:49 in this video): /var/www/basic-flask-app/logs/error.log
You can also check your default Apache error log, which should live here: /var/log/apache2/error.log
If the server is giving you a big server error when you visit the URL, then the server is logging more details about the error somewhere. Probably in one of these two files.
@@LukePeters Sorry Luke, I have solved the error, thanks for suggesting to look in error.logs
@@parthpandey4631 No need to apologize! I'm glad looking in the error log helped 😃
Hey, have you ever achieved to deploy a flask app with flask-socketio to a server and run it?
Hey Niko, yes I have, but not in a long time. I don’t remember if it was difficult or not. Maybe I should do a video on this.
Thanks for the video, I was able to deploy the app on the apache server, however with apache I cannot connect to SQL Server, although the configuration is correct. But if I launch the app from the cmd everything works, does anyone know why?
Check the error logs! There's a specific error message or error code being stored somewhere, which is a great place to start debugging. Too many possible reasons for a failure to connect.
@@LukePeters Same error for me, apparently we should do something to include for example sqlalchemy, it simply does not commit or query anything from the db file
@@adrianrs79 Did you check your app's error logs? What about the general Apache error logs?
You can also implement your own logging within Flask. Follow these steps: snipsave.com/user/lukepeters/snippet/9a7HzD5gyzYxJybWru/ Then you will hopefully see some kind of database errors in the "debug.log" file after trying to load/use your app again.
4:01 Why hardcode the path when we can make a "pwd" from the the very app?
You can use any method you’d like to get the correct path in there. I used an absolute path for simplicity.
I was able to install everything without any errors. I am facing some issue after starting the apache server and trying to access the server from chrome. Am getting two errors in the error log:
1] PermissionError: [Errno 13] Permission denied: '/root/.local/share/virtualenvs/OnlineLearner-uZdfk3kh/bin/activate_this.py'
2] Target WSGI script '/var/www/OnlineLearner/app.wsgi' cannot be loaded as Python module.
Please help me out Luke. Thanks in advance!!
Hey Sudesh! Can you check whether Apache has permission to read/write the virtualenvs/ directory? On Ubuntu/Debian servers, Apache runs as the user "www-data" under the group "www-data" by default. In this case, you might do something like this: sudo chown -R www-data /root/.local/share/virtualenvs
Or you could just change the directory's group to the same as Apache: sudo chgrp -R www-data /root/.local/share/virtualenvs
Or you could run Apache under your own username (or whichever username CURRENTLY owns the virtualenvs/ directory). Check out this article to learn how to change which user/group Apache runs as: www.simplified.guide/apache/change-user-and-group
And to find out which user CURRENTLY owns the virtualenvs/ directory do this: ls -ld /root/.local/share/virtualenvs
I know that's a lot, but I hope it helps!
Whats the advantage to deploy a flask application with wsgi? Im new in flask…
WSGI helps tell an Apache web server how to run the Flask app. Without WSGI, Apache wouldn't know what to do with a bunch of Python files.
hi, excelente video, but i have problems in deploy on debian 11 ... yu can help me ??? .. I do not receive any data in the request through post ...
Thank you! The very first thing you need to do is check the Apache error logs. They should contain more information about what isn’t working.
In this video in the .conf file we specified a custom error log path. Check that file for more information.
You can also check the default Apache logs for more information: /var/log/apache2/error.log
Without more information from an error log and without seeing your code it’s impossible to know why it’s not working.
@@LukePeters that's a problem, the error log shows nothing, my api runs fine in development mode and runs in production, but now I don't know if WSGI blocks input data or something like that
thanks for answer
greetings
thank you, i need to migrate a flask app running on windows, and look like i need some extra steps
Hey Luke, thanks for the great tutorial!
I've been able to deploy my website :))
I'm struggling with the error: app called on a post request cannot connect to X server. It runs perfectly on pycharm, but throws this error on the deployed version. I have changed the wsgi user,, exported the app to $PATH but no success. I read every related post on stackoverflow...
Would you give me a hint on that? Thanks
Hey Caio! I'm glad this tutorial was helpful!
I did a little research on your error message. Is your Python app doing anything that requires a computer screen/display? Like taking a screenshot, or something else?
In Linux, "X" is an application that manages graphics displays and input devices (like mice and keyboards).
If your app utilizes the graphics card/display in some way, you may need to configure it to run in some kind of "headless" mode on the production server.
@@LukePeters
Thanks for checking up on that. Yes, the flask app provides a web interface for a system that analyzes biomedical images. With user input, the flask app calls another app that pre-processes, infers (DL) and post-processes the uploaded raw image. This second app needs access to the display system (X-server).
I know that might raise security issues, but that is the best way I have so far. I'm adding other security layers to limit the risks.
The way I sorted that out was adding the line "os.environ["DISPLAY"] = ":1"" to the wsgi file (my $DISPLAY is :1) and it worked great. I'm now working on a dockerized xvfb solution to that, which I guess can reduce the risk a little more.
Great channel, thanks again!
@@caioathayde6498 Glad you found a solution that works for your use case!
generated an error because apache does not have permission to enable virtualenv
Has anyone had this problem?
Hey Lucas, can you share the exact error message you're getting?
@@LukePeters Hay Luke I was wondering if you have found the answer to this question. I seem to be having the same issue and not sure why. The issue seems to be that open can not access the virtual environment activate_this.py file. Thanks and amazing video :)
Same problem for me as well also tried changing permissions with chmod but it already have permission i guess
@@warhawk3895 Hey! I can't help without a specific error message. There are many possible causes, many of them personal environment configuration issues which can be different for everyone.
Try to change WSGIDaemonProcess user and group to user and group of what u create venv in .conf file
how can we set os.environ variables?
By typing 'os.environ' like you just did 😄
import os
os.environ['username'] = 'GokEnsar'
@@LukePeters No, i didn't mean that, like i want to set environ variables not in code but somewhere like .env file
@@GokEnsar Ah gotcha, this article should be what you're looking for: dev.to/sasicodes/flask-and-env-22am
@@LukePeters thank you.
@@GokEnsar For sure 👍🏻
thanks
best
I got internal server error
So… Did you read your server logs then?
@@LukePeters I haven't use virtual env will it be fine? And also i am doing this as root user it that okay ? Will it still work?
@@LukePeters #!/usr/bin/python3
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/cwh/"
from cwh import app as application
application.secret_key = 'Add-secret'
i used this code in wsgi file
@@fahadshaikh9715 You don’t need to use a virtual environment if you a don’t want to. And root user isn’t an amazing idea for security, but it will totally work.
Wow, why did you delete my comments?
What is my wrong?
I am very grateful to you for the video...
I didn't delete anything...
this makes me think machine learning is easier
Hey Sulav, what do you mean? Did this video make sense?
I just get a 404 no matter what. ugh
Sorry to hear that! I can't help with such little information, though 😅 Look at your APACHE ERROR LOGS! There's a clue somewhere. It's not just silently failing.
I am trying to run a Flask app on my raspberry with apache. Because this app sometimes needs GPIO-access, I can't run it without sudo. How can I tell apache to sudo run it? Or is there a better way?
I also run into some problems when accessing the machine with its hostname instead of the IP.
I then get the "Apache2 Debian Default Page" - unless I change line 4 in the .conf file.
With WSGIScriptAlias /{path} /var/www/basic-flask-app/app.wsgi the error doesn't occurs.
But then I have to call {hostname}.local/{path} instead of just {hostname}.local
Do you have any idea how to solve this? I am working with a Raspberry Pi Zero as I mentioned above
Thanks for the nice tutorial though!
Deleting/moving/renaming the /var/www/html/index.html already did the trick, but im not sure if that's the best solution
"Cannot access directory '/var/www/html/logs/' for error log of vhost defined at /etc/apache2/sites-enabled/basic-flask-app.conf:1"
I got this king for error while configtest Bro can you give a solution ???
It looks like Apache cannot access that directory. If the directory exists, it's probably a permissions error.
Find out what user/group Apache runs as by looking at the /etc/apache2/envvars file. They're listed in there as APACHE_RUN_USER and APACHE_RUN_GROUP.
Then make sure /var/www/html/logs is owned by the same user or group. If the user is 'www-data', do this: 'sudo chown www-data /var/www/html/logs -R'