I would like to make the default port that manage.py runserver listens on specifiable in an extraneous config.ini. Is there an easier fix than parsing sys.argv inside manage.py and inserting the configured port?
The goal is to run ./manage.py runserver without having to specify address and port every time but having it take the arguments from the config.ini.
create a bash script with the following:
#!/bin/bash
exec ./manage.py runserver 0.0.0.0:<your_port>
save it as runserver in the same dir as manage.py
chmod +x runserver
and run it as
./runserver
Actually the easiest way to change (only) port in development Django server is just like:
python manage.py runserver 7000
that should run development server on http://127.0.0.1:7000/
As of Django 1.9, the simplest solution I have found (based on Quentin Stafford-Fraser's solution) is to add a few lines to manage.py which dynamically modify the default port number before invoking the runserver command:
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.dev")
import django
django.setup()
# Override default port for `runserver` command
from django.core.management.commands.runserver import Command as runserver
runserver.default_port = "8080"
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
All of the following commands are possible to change the port while running django:
python manage.py runserver 127.0.0.1:7000
python manage.py runserver 7000
python manage.py runserver 0:7000
Create a subclass of django.core.management.commands.runserver.Command and overwrite the default_port member. Save the file as a management command of your own, e.g. under <app-name>/management/commands/runserver.py:
from django.conf import settings
from django.core.management.commands import runserver
class Command(runserver.Command):
default_port = settings.RUNSERVER_PORT
I'm loading the default port form settings here (which in turn reads other configuration files), but you could just as well read it from some other file directly.
you can try to add an argument in manage.py like this
python manage.py runserver 0.0.0.0:5000
python manage.py runserver <your IP>:<port>
or you pass the port like this
python manage.py runserver 5000
python manage.py runserver <your port>
We created a new 'runserver' management command which is a thin wrapper around the standard one but changes the default port. Roughly, you create management/commands/runserver.py and put in something like this:
# Override the value of the constant coded into django...
import django.core.management.commands.runserver as runserver
runserver.DEFAULT_PORT="8001"
# ...print out a warning...
# (This gets output twice because runserver fires up two threads (one for autoreload).
# We're living with it for now :-)
import os
dir_path = os.path.splitext(os.path.relpath(__file__))[0]
python_path = dir_path.replace(os.sep, ".")
print "Using %s with default port %s" % (python_path, runserver.DEFAULT_PORT)
# ...and then just import its standard Command class.
# Then manage.py runserver behaves normally in all other regards.
from django.core.management.commands.runserver import Command
In Pycharm you can simply add the port to the parameters
first you apply the migrations for app
python manage.py migrate
then:
python manage.py runserver <your port>
after in browser run 127.0.0.1:(your port)
in the last version of Django(Right now: 4.0.3), you can add these lines to your settings.py file
from django.core.management.commands.runserver import Command as runserver
runserver.default_port = "8000"
in your project manage.py file add
from django.core.management.commands.runserver import Command as runserver
then in def main():
runserver.default_port = "8001"
I'm very late to the party here, but if you use an IDE like PyCharm, there's an option in 'Edit Configurations' under the 'Run' menu (Run > Edit Configurations) where you can specify a default port. This of course is relevant only if you are debugging/testing through PyCharm.
Create enviroment variable in your .bashrc
export RUNSERVER_PORT=8010
Create alias
alias runserver='django-admin runserver $RUNSERVER_PORT'
Im using zsh and virtualenvs wrapper. I put export in projects postactivate script and asign port for every project.
workon someproject
runserver
If you wish to change the default configurations then follow this steps:
Open terminal type command
$ /usr/local/lib/python<2/3>.x/dist-packages/django/core/management/commands
Now open runserver.py file in nano editor as superuser
$ sudo nano runserver.py
find the 'default_port' variable then you will see the default port no is '8000'. Now you can change it to whatever you want.
Now exit and save the file using "CTRL + X and Y to save the file"
Note: Replace <2/3>.x with your usable version of python
For Django 3.x, just change default_port in settings.py. Like this:
from decouple import config
import django.core.management.commands.runserver as runserver
runserver.Command.default_port = config('WebServer_Port', default = "8088")
Then, if you want to specify the port, just add a new line in your setting.ini
[settings]
WebServer_Port=8091
If not, delete this parameter.
This is an old post but for those who are interested:
If you want to change the default port number so when you run the "runserver" command you start with your preferred port do this:
Find your python installation. (you can have multiple pythons installed and you can have your virtual environment version as well so make sure you find the right one)
Inside the python folder locate the site-packages folder. Inside that you will find your django installation
Open the django folder-> core -> management -> commands
Inside the commands folder open up the runserver.py script with a text editor
Find the DEFAULT_PORT field. it is equal to 8000 by default. Change it to whatever you like
DEFAULT_PORT = "8080"
Restart your server: python manage.py runserver and see that it uses your set port number
It works with python 2.7 but it should work with newer versions of python as well. Good luck
I was struggling with the same problem and found one solution. I guess it can help you.
when you run python manage.py runserver, it will take 127.0.0.1 as default ip address and 8000 as default port number which can be configured in your python environment.
In your python setting, go to <your python env>\Lib\site-packages\django\core\management\commands\runserver.py and set
1. default_port = '<your_port>'
2. find this under def handle and set
if not options.get('addrport'):
self.addr = '0.0.0.0'
self.port = self.default_port
Now if you run "python manage.py runserver" it will run by default on "0.0.0.0:
Enjoy coding .....
I'm trying to deploy a Flask app on Google Compute Engine. I have it all configured, but when I try to deploy it with gcloud app deploy, it says ModuleNotFoundError: No module named 'main'. This is my file structure:
└── gpt-redteam-api/
├── app.yaml
├── main.py
└── ...other files
and I am deploying it from inside gpt-redteam-api. Is this a common problem/are there any elementary fixes I’m missing?
For your issue you need to add a custom entrypoint to recognize the main.py
Entrypoint: Optional. Overrides the default startup behavior by executing the entrypoint command when your app starts. For your app to receive HTTP requests, the entrypoint element should contain a command which starts a web server that listens on port 8080.
You need to configure the entrypoint field by the following steps.
This line says to look for the variable named app in the module named main.py:
entrypoint: gunicorn -b:$PORT main:app
You could either rename your app.py to main.py or update this line to:
entrypoint: gunicorn -b:$PORT app:app
For more information follow this doc and refer to this stack question also.
I'm trying to migrate a Django application from Google Kubernetes Engine to Google Cloud Run, which is fully managed. Basically, with Cloud Run, you containerize your application into a single Dockerfile and Google does the rest.
I have a Dockerfile which at one point does call a bash script via ENTRYPOINT
But I need to start Nginx and start Gunicorn. The Google Cloud Run documentation suggest starting Gunicorn like this:
CMD gunicorn -b :$PORT foo.wsgi
(let's sat my Django app is named "foo")
But I also need to start Nginx via:
CMD ["nginx", "-g", "daemon off;"]
And since only one CMD is allowed per Dockerfile, I'm not sure how to combine them.
To try to get around some of these difficulties, I was looking into using a Dockerfile to build from that already has both working and I came across this one:
https://github.com/tiangolo/meinheld-gunicorn-docker
But the paths don't quite match mine. Quoting from the documentation of that repo:
You don't need to clone the GitHub repo. You can use this image as a
base image for other images, using this in your Dockerfile:
FROM tiangolo/meinheld-gunicorn:python3.7
COPY ./app /app It will expect a file at /app/app/main.py.
And will expect it to contain a variable app with your "WSGI"
application.
My wsgi.py file ends up at /app/foo/foo/wsgi.py and contains an application named application
But if I understand that documentation correctly, when it says it will expect the WSGI application to be named app and to be located at /app/app/main.py it's basically saying that I need to revise the path and the variable name so that when it builds the image it knows that app is called application and that instead of finding it at /app/app/main.py it will find it at /app/foo/foo/wsgi.py
I assume that I can fix the app vs application variable name by adding a line to my wsgi.py file like app = application but I'm not sure how to correct the path that Docker expects.
Can someone explain to me how to adapt this to my needs?
(Or any other way to get it working)
I am developing a web application with React for frontend and Django for backend. I use Webpack to watch for changes and bundle code for React apps.
The problem is that I have to run two commands concurrently, one for React and the other one for Django:
webpack --config webpack.config.js --watch
./manage.py runserver
Is there any way to customize runserver command to execute the npm script, like npm run start:dev? When you use Node.js as a backend platform, you can do the similar job like npm run build:client && npm run start:server.
If you are already using webpack and django, probably you can be interested in using webpack-bundle-tracker and django-webpack-loader.
Basically webpack-bundle-tracker will create an stats.json file each time the bundle is build, and django-webpack-loader will watch for those stats.json file to relaunch the dev server. This stack allows to separate the concerns between the server and the client.
There are a couple of posts out there explaining this pipeline.
I'm two and a half years late, but here's a management command that implements the solution that OP wanted, rather than a redirection to another solution. It inherits from the staticfiles runserver and runs webpack concurrently in a thread.
Create this management command at <some_app>/management/commands/my_runserver.py:
import os
import subprocess
import threading
from django.contrib.staticfiles.management.commands.runserver import (
Command as StaticFilesRunserverCommand,
)
from django.utils.autoreload import DJANGO_AUTORELOAD_ENV
class Command(StaticFilesRunserverCommand):
"""This command removes the need for two terminal windows when running runserver."""
help = (
"Starts a lightweight Web server for development and also serves static files. "
"Also runs a webpack build worker in another thread."
)
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument(
"--webpack-command",
dest="wp_command",
default="webpack --config webpack.config.js --watch",
help="This webpack build command will be run in another thread (should probably have --watch).",
)
parser.add_argument(
"--webpack-quiet",
action="store_true",
dest="wp_quiet",
default=False,
help="Suppress the output of the webpack build command.",
)
def run(self, **options):
"""Run the server with webpack in the background."""
if os.environ.get(DJANGO_AUTORELOAD_ENV) != "true":
self.stdout.write("Starting webpack build thread.")
quiet = options["wp_quiet"]
command = options["wp_command"]
kwargs = {"shell": True}
if quiet:
# if --quiet, suppress webpack command's output:
kwargs.update({"stdin": subprocess.PIPE, "stdout": subprocess.PIPE})
wp_thread = threading.Thread(
target=subprocess.run, args=(command,), kwargs=kwargs
)
wp_thread.start()
super(Command, self).run(**options)
For anyone else trying to write a command that inherits from runserver, note that you need to check for the DJANGO_AUTORELOAD_ENV variable to make sure you don't create a new thread every time django notices a .py file change. Webpack should be doing it's own auto-reloading anyway.
Use the --webpack-command argument to change the webpack command that runs (for example, I use --webpack-command 'vue-cli-service build --watch'
Use --webpack-quiet to disable the command's output, as it can get messy.
If you really want to override the default runserver, rename the file to runserver.py and make sure the app it lives in comes before django.contrib.static in your settings module's INSTALLED_APPS.
You shouldn't mess with the built-in management commands but you can make your own: https://docs.djangoproject.com/en/1.10/howto/custom-management-commands/.
On your place I'd leave runserver in place and create one to run your custom (npm in this case) script, i.e. with os.execvp.
In theory you could run two parallel subprocesses one that would execute for example django.core.management.execute_from_command_line and second to run your script. But it would make using tools like pbd impossible (which makes work very hard).
The way I do it is that I leverage Docker and Docker compose. Then when I use docker-compose up -d my database service, npm scripts, redis, etc run in the background (running runserver separately but that's another topic).
I have a Django site running in Docker containers, which uses docker-compose to manage the various containers (database, nginx, etc.). There are a few Django tasks that I use for site maintenance using the Django manage.py command. They commands take the form of:
manage.py updateflickr --settings=mysite.myproj.prod
Running under docker-compose, they look like:
docker-compose run --rm app manage.py updateflickr --settings=mysite.myproj.prod
My problem is that when I try to run these same commands using Fabric, it appears that the settings file I am specifying is not being used. Django is returning database connection errors, which typically mean that it is not getting the correct database information, or in this case the connection specified in mysite.myprod.prod
My Fabric file looks like:
import os
from fabric.api import *
env.hosts = ['myserver.com']
env.user = "myuser"
env.key_filename = '~/.ssh/do_rsa'
env.shell = '/bin/bash -c'
#task
def updateflickr():
run('docker-compose run --rm app python manage.py updateflickr --settings=mysite.myproj.prod')
I have also expirimented with setting the DJANGO_SETTINGS_MODULE environment variable in my docker-compose.yml but am getting the same results. Finally, the last thing I tried was wrapping the command in a shell script. Same results - if I run on the server, it runs fine. If I run the shell script from Fabric, I get database connection issues.
UPDATE
I am not so sure this is so much a question about Fabric, then a question about how docker-compose runs. If I try the following:
ssh -t me#myserver.com 'docker-compose run --rm app python manage.py updateflickr --settings=mysite.myproj.prod'
I still get the same results. There must be something different about loading up an interactive shell with just sending a command. I have tried using ssh with and without a -t flag, because docker-compose might need a pty active.