I'm trying to run a django server from gulp. Although I've now managed (roughly) to activate the virtual env and then start the server, none of the output/errors from the django server appears. How can I get this to appear when using gulp?
gulpfile.js
var pjson = require('./package.json');
// Run django server
var cmd = 'workon switcher5'
gulp.task('runServer', function() {
exec('~/virtualenvs/' + pjson.name + '/bin/python manage.py runserver', function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
});
});
Note although the server runs fine. I am getting the error in the console:
/bin/sh: /Users/User/virtualenvs/switcher5/bin/python: No such file or directory
(Running the django server not via gulp works as normal. )
I tried to spawn a process instead:
gulp.task('runServer', function(){
console.info('starting django server');
var PIPE = {stdio: 'inherit'};
spawn('~/virtualenvs/' + pjson.name + '/bin/python', ['manage.py', 'runserver'], PIPE);
});
However although that ran with
spawn('python', ['manage.py', 'runserver'], PIPE);from the terminal (activating virtualenv before manually running via the above fails.
I'm not clear what's wrong with the path (if anything)
When it ran from the terminal it now gives output, but seems to be only errors from the django server (304's etc...), but no successful requests appear.
I have struggled with this exact concept for a while. The examples that I've seen have everything all in one gulpfile.js, where I have things more modular. Additionally, I had it working with a prior Django project, but then broke it with my next project when I followed the Two Scoops method of breaking up your configuration files.
I finally got it working by creating the files below (Windows-based machine) and then running 'gulp watch' from the bash command line:
Basic Project Folder Structure:
root folder
|_ project folder
|_ config folder
|_ gulp
|_ tasks
runserver.js
watch.js
|_ gulpfile.js
gulpfile.js:
// Load gulp script modules
require('./gulp/tasks/runserver');
require('./gulp/tasks/watch');
runserver.js
// Starts python django server
// Import packages
var gulp = require('gulp'),
spawn = require('child_process').spawn;
// Start the Django runserver
gulp.task('startDjango', function(cb){
var projDir = 'C:\\<<project folder>>'
var envDir = 'C:\\<<virtual environment directory>>'
var cmd = spawn('python', [projDir + '\\manage.py', 'runserver'],
{cwd: envDir, stdio: 'inherit'}
);
cmd.on('close', function(code) {
console.log('startDjango exited with code ' + code);
cb(code);
});
});
watch.js:
// Kicks off Django server, opens and syncs browser upon changes
// Import packages
var gulp = require('gulp'),
watch = require('gulp-watch'),
browserSync = require('browser-sync').create();
// WATCH for changes to files
gulp.task('watch', function(){
// Start python django server
gulp.start('startDjango');
// Sync browsers to python runserver
browserSync.init({
notify: false,
localOnly: true,
proxy: {
target: 'http://localhost:8000/',
},
port: process.env.PORT || 8000,
});
// Refresh the browser whenever any HTML file is changed
watch('./**/*.html', function(){
browserSync.reload();
});
... // Other watch activities here
});
Hope this helps anyone else who's struggling. :)
The key issue in the question was to get gulp to launch a virtualenv then launch the django server while passing the output from it to node via stdout.
The other answer mention unfortunately doesn't achieve this as it doesn't launch a virtualenv at the same time.
The solution below, does work.
(note if you don't use virtualenv in a venv/ folder then just adjust the below to the relevant location
// Activates a virtualenv and runs django server
gulp.task('runServer', function(cb) {
var cmd = spawn('venv/bin/python', ['manage.py', 'runserver'], {stdio: 'inherit'});
cmd.on('close', function(code) {
console.log('runServer exited with code ' + code);
cb(code);
});
});
Related
void reg() async {
try{
http.Response response = await http.get(Uri.parse("http://10.0.2.2/api/alluser"));
print(response.body);
}
catch(e){
print(e);
}
}
It is working when I am doing in chrome( web) http://127.0.0.1:8000 but not working in android emulator.
in Django's setting.py
ALLOWED_HOST = [10.0.2.2 , 127.0.0.1]
NOTE - Specific for connecting Android and django rest api in Flutter
I tried lot of things but connection timeout was occuring. I was using django Rest-Api
go to Command Prompt type ipconfig copy ipv4 address in my case 192.168.2.4.
add 192.168.2.4 in ALLOWED_HOST =[] in django settings.py.
type "python manage.py runserver 192.168.2.4:8000" to run your server.
4)In Flutter
your baseurl for accesing django rest api should be "http://192.168.2.4:8000/"
This worked for me . thanks
So im trying to deploy a django app with nginx and uwsgi , ngnix is running well and the django app is working well with manage.py runserver , but when i try to deploy it with uwsgi it said Internal Server Error , and when i check my uwsgi logs that what i get (No module named django)
the virtualenv python version is 3.6.9 ,i'dont know if this error is caused because of imcompatibilty with python version of virtual environement and the Uwsgi one or just because i missed somethings , my uwsgi specs are
this is my uwsgi ini file :
[uwsgi]
vhost = true
plugins = python
socket = /tmp/mainsock
master = true
enable-threads = true
processes = 4
wsgi-file = /var/www/PTapp-launch/ptapp/wsgi.py
virtualenv = /var/www/venv/site
chdir = /var/www/PTapp-launch
touch-reload = /var/www/PTapp-launch/reload
env = DJANGO_ENV=production
env = DATABASE_NAME=personal_trainer
env = DATABASE_USER=postgres
env = DATABASE_PASSWORD=********
env = DATABASE_HOST=localhost
env = DATABASE_PORT=5432
env = ALLOWED_HOSTS=141.***.***.***
i have finally found the problem , when i was running manage.py runserver i had to use sudo , but when i didnt it was throwing the same error , (no module named Django) , so what i did its i uninstall all requirements and then use super user to create new virtual environnement and link it in uwsgi.ini, i also restart both of nginx and uwsgi, so everything work fine now ...
I've been trying to set up a React component inside Django with the help of Webpack 4.
To get me starting I went through and read:
Using Webpack transparently with Django + hot reloading React components as a bonus
Tutorial: Django REST with React (Django 2.0 and a sprinkle of testing)
Both these walkthroughs are great. At last, I got it almost working by following the second link even though I use Django 1.11.
The problem I had after following the second link was that hot reloading does not work when using a webpack-dev-server. The problem is that Django cannot read the output file of the webpack-dev-server (gives 404 error) while the main.js can be read. I've read that the dev-server files do only live in memory by default.
To overcome the issue with error 404 on the hot reload files I installed the package write-file-webpack-plugin to write out the file each reloads. Then changed the webpack-config.js to (I deleted some lines to keep it shorter....):
var path = require('path');
//webpack is not needed since I removed it from plugins
//const webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');
var WriteFilePlugin =require('write-file-webpack-plugin');
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
]
},
entry: [
'./frontend/src/index',
],
output: {
path: path.join(__dirname, 'frontend/static/frontend'),
// Changing the name from "[name]-[hash].js" to not get 1000 files in the static folder.
filename: 'hotreloadfile.js'
},
plugins: [
//This line writes the file on each hot reload
new WriteFilePlugin(),
//This can be removed.
//new webpack.HotModuleReplacementPlugin(),
new BundleTracker({filename: './webpack-stats.json'})
],
mode:'development',
};
in my package.json I have the follow line among the script tag:
"start": "webpack-dev-server --config ./webpack.config.js",
And in Django I installed webpack-loader with the following lines in settings.py:
STATIC_URL = '/static/'
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'frontend/',
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json')
}
}
Finally, in my root component called index.js, I do not need the module.hot.accept(); line
Do you see any drawbacks to this approach? Except that I had to install another package?
Why didn't I get it to work with new webpack.HotModuleReplacementPlugin()?
Here is another approach if you develop frontend in react and backend in django.
I have django server running on port 8000 and react server running on port 3000.
If I add "proxy": "http://localhost:8000" line in package.json of react code, localhost:3000 will do hot-reloading while api call goes to localhost:8000.
I created several servers, without any issue, with the stack nginx - uwsgi - flask using virtualenv.
with the current one uwsgi is throwing the error cannot import name "appl"
here is the myapp directory structure:
/srv/www/myapp
+ run.py
+ venv/ # virtualenv
+ myapp/
+ init.py
+ other modules/
+ logs/
here is the /etc/uwsgi/apps-avaliable/myapp.ini
[uwsgi]
# Variables
base = /srv/www/myapp
app = run
# Generic Config
# plugins = http, python
# plugins = python
home = %(base)/venv
pythonpath = %(base)
socket = /tmp/%n.sock
module = %(app)
callable = appl
logto = %(base)/logs/uwsgi_%n.log
and this is run.py
#!/usr/bin/env python
from myapp import appl
if __name__ == '__main__':
DEBUG = True if appl.config['DEBUG'] else False
appl.run(debug=DEBUG)
appl is defined in myapp/ _ init _ .py as an instance of Flask()
(underscores spaced just to prevent SO to turn them into bold)
I accurately checked the python code and indeed if I activate manually the virtualenvironment and execute run.py manually everything works like a charm, but uwsgi keeps throwing the import error.
Any suggestion what should I search more ?
fixed it, it was just a read permissions issue. The whole python app was readable by my user but not by the group, therefore uwsgi could not find it.
This was a bit tricky because I deployed successfully many time with the same script and never had permissions issues
I'm using Django served by uWSGI and NGINX.
Ubuntu 14.04.1 LTS 64-bit
Python 3.4
Django 1.7.4
uWSGI 1.9.17.1-debian (64bit)
NGINX 1.4.6
python-pdfkit 0.5.0
wkhtmltopdf 0.12.2.1
OpenLayers v3.0.0
When I try running pdfkit.from_url(...) to print a map to pdf the request times out.
More specifically it hangs in python's subprocess.py communicate, self._communicate:
with _PopenSelector() as selector:
if self.stdin and input:
selector.register(self.stdin, selectors.EVENT_WRITE)
if self.stdout:
selector.register(self.stdout, selectors.EVENT_READ)
if self.stderr:
selector.register(self.stderr, selectors.EVENT_READ)
while selector.get_map():
...
selector.get_map() always returns a valid result, ensuring an infinite loop.
If I run this in the Django development server (instead of uWSGI+NGINX) everything runs fine.
in my view:
wkhtmltopdfBinLocationString = '/usr/local/bin/wkhtmltopdf'
wkhtmltopdfBinLocationBytes = wkhtmltopdfBinLocationString.encode('utf-8')
#this fixes some leftover python2 assumptions about strings
config = pdfkit.configuration(wkhtmltopdf=wkhtmltopdfBinLocationBytes)
pdfkit.from_url(reportPdfUrl, reportPdfFile, configuration=config, options={
'javascript-delay': 1500
})
Several places I have seen answers along the line of "set the close-on-exec flag on the socket" solving similar issues.
Is this something I can set from my "from_url" options (wkhtmltopdf does not accept it by that name) or can I configure uWSGI to assume 'close-on-exec'? I have not been able to make either of these work, but maybe I just need help with changing my uWSGI customization file:
[uwsgi]
workers = 1
chdir = [...]
plugins = python34
wsgi-file = [...]/wsgi.py
pythonpath = [...]
I tried something like
close-on-exec = true
but that didn't seem to do anything.
NOTE: the wsgi.py file is simple:
"""
WSGI config for dst project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "[my_project].settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
Any thoughts?