from flask import Flask, render_template, request, url_for, g
app = Flask(__main__)
# This is the entrypoint
#app.route('/')
def index():
# Render page
return 'Hello'
if __name__=='__main__':
app.run(debug=True)
When I try to run this in the VSCode debugger I get:
* Serving Flask app 'gui' (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
No module named gui
I set a breakpoint on the line "app.run(debug=True)" and it does execute to that point but when I try to step over or into I get the error.
I tried changing the name of the file from gui.py to app.py and I got the same thing except it says:
* Serving Flask app 'app' (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
No module named app
What am I doing wrong/missing?
To debug flask with VSCode you need to set your setting.json and launch.json files correctly, here is a possible configuration:
settings.json
{
"python.pythonPath": "<your_python_venv_path>",
}
launch.json
{
"version": "0.2.0",
"configurations" : [
{
"name": "local",
"type": "python",
"stopOnEntry": false,
"request": "launch",
"program" : "${workspaceFolder}/<path_to_run.py>",
"console" : "integratedTerminal",
"justMyCode" : false,
"cwd": "${workspaceFolder}"
}
]
}
Also take a look here
Related
I'm currently trying to setup a Google app engine flex using a django framework with django-channels. for my current project i need a websocket, so i'm trying to reconstruct the tutorial offered on the website by Django-channels: https://channels.readthedocs.io/en/latest/tutorial/
Currently I'm stuck on adding redis to my google-app-flex instance. I followed the google documentation on setting up a redis connection - unfortunatly the example is in Flask: google doc
I assume my error is trivial, and i just need to connect django CHANNEL_LAYERS to redis proporly.
executing sudo gcloud redis instances describe <redisname> --region=us-central1 gives me following responce:
Image: "Redis Describtion"
executing sudo gcloud app describe, this responce:
I configured my app.yaml as follows:
# app.yaml
# [START runtime]
runtime: python
env: flex
entrypoint: daphne django_channels_heroku.asgi:application --port $PORT --bind 0.0.0.0
runtime_config:
python_version: 3
automatic_scaling:
min_num_instances: 1
max_num_instances: 7
# Update with Redis instance IP and port
env_variables:
REDISHOST: '<the ip in "host" from "Redis Describtion" image above>'
REDISPORT: '6379'
# Update with Redis instance network name
network:
name: default
# [END runtime]
..and in my settings.py i added this as the redis connection (which feels really wrong btw):
#settings.py
import redis
#settings.py stuff...
#connect to redis
redis_host = os.environ.get('REDISHOST', '127.0.0.1')
redis_port = int(os.environ.get('REDISPORT', 6379))
redis_client = redis.StrictRedis(host=redis_host, port=redis_port)
# Channels
ASGI_APPLICATION = "django_channels_heroku.routing.application"
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
what am i doing wrong. how do i connect to Redis using Django correctly?
here are some Links:
https://cloud.google.com/memorystore/docs/redis/connect-redis-instance-flex
Django, Redis: Where to put connection-code
Deploying Django channels app on google flex engine
How to connect to Redis instance (memorystore) from Google's Standard App Engine (Python 3.7)
https://cloud.google.com/memorystore/docs/redis/connect-redis-instance-flex
https://cloud.google.com/memorystore/docs/redis/quickstart-gcloud
My mistake is in the settings.py:
Correct version:
#settings.py
#settings stuff...
redis_host = os.environ.get('REDISHOST', '127.0.0.1')
redis_port = int(os.environ.get('REDISPORT', 6379))
#redis_client = redis.StrictRedis(host=redis_host, port=redis_port) #this is not needed
# Channels
ASGI_APPLICATION = "django_channels_heroku.routing.application"
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [(redis_host, redis_port)],
},
},
}
When I run a debug configuration in VS Code:
"configurations": [
{
"name": "Django Tests",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/src/manage.py",
"args": [
"test",
"src"
],
"django": true
}
I get this error:
django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known
I don't have this problem when I run the app normally:
./src/manage.py runserver
db is my containerized postgresql database.
services:
db:
container_name: db
build: ./postgresql
expose:
- "5432"
ports:
- 5432:5432
...
Perhaps I'm not using the proper python path? I should be running this from within my python virtual environment but I'm not sure how to set that in the VS Code configuration, if that's the problem.
Here's my settings.py
POSTGRES_HOST = os.environ.get('POSTGRES_HOST', '127.0.0.1')
POSTGRES_PORT = os.environ.get('POSTGRES_PORT', '5432')
It seems like db is visible locally:
$ docker logs db
PostgreSQL Database directory appears to contain a database; Skipping initialization
Here's the command CS Code runs when I try to choose the debug configuration:
(venv) me#host:/path/to/myproject/$ env DEBUGPY_LAUNCHER_PORT=36867 /path/to/myproject/venv/bin/python3 /home/me/.vscode/extensions/ms-python.python-2020.3.71659/pythonFiles/lib/python/debugpy/no_wheels/debugpy/launcher /path/to/myproject/src/manage.py runserver --noreload
you need to make sure vs-code can find the host db or uses 127.0.0.1 directly.
In youre case overriding the environment "envFile": "" did the trick.
I am trying to implement a debugging plugin ptvsd into my existing dockerized application
Running on Google Compute Engine with Ubuntu 18.04. The entire application is containerized with Docker-Compose. Back-end Plugin: Django
manage.py:
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
import ptvsd
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoserver.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
ptvsd.enable_attach(address=('0.0.0.0', 5050))
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
Launch.json
{
"name": "Attach Remote Django",
"type": "python",
"request": "attach",
"pathMappings": [
"localRoot": "${workspaceRoot}/djangoserver",
"remoteRoot": "/usr/src/"
],
"port": 5050,
"secret": "secret",
"host": "localhost"
}
docker-compose.yml
web:
build: ./djangoserver
command: gunicorn djangoserver.wsgi:application --noreload --nothreading --bind 0.0.0.0:8001
volumes:
- ./djangoserver:/usr/src
# entrypoint: /entrypoint.sh
ports:
- 5050:5050
expose:
- 8001
env_file: .env.dev
depends_on:
- db_development_2
stdin_open: true
Whenever i a do build and run the docker-composer, it starts without any problems, but later on, when I am trying to connect to the server with the debugger, I receive following error:
Failed to attach (connect ECONNREFUSED 127.0.0.1:5050)
I've built a simple SPA CRUD web app with Django, Vue and Docker(-compose).
Since I've finished developing the app, I'm now preparing for the production environment, that is, using bundle.js and bundle.css files.
When I try to load the main page, http://localhost:8000, no CSS or JS
are being loaded because I'm getting this error in the browser's console:
GET http://0.0.0.0:8080/bundle.css net::ERR_CONNECTION_REFUSED
GET http://0.0.0.0:8080/bundle.js net::ERR_CONNECTION_REFUSED
I really don't know why it is giving that error or how to fix it.
This is my vue.config.js file:
const webpack = require("webpack");
const BundleTracker = require("webpack-bundle-tracker");
module.exports = {
publicPath: "http://0.0.0.0:8080/",
outputDir: "./dist/",
filenameHashing: false,
configureWebpack: {
plugins: [
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1
})
]
},
chainWebpack: config => {
config
.plugin("BundleTracker")
.use(BundleTracker, [{ filename: "./webpack-stats.json" }]);
config.output.filename("bundle.js");
config.optimization.splitChunks(false);
config.optimization.delete("splitChunks");
config.resolve.alias.set("__STATIC__", "static");
config.devServer
.hotOnly(true)
.watchOptions({ poll: 1000 })
.https(false)
.disableHostCheck(true)
.headers({ "Access-Control-Allow-Origin": ["*"] });
},
// uncomment before executing 'npm run build'
css: {
extract: {
filename: "bundle.css",
chunkFilename: "bundle.css"
}
}
};
This is part of my settings.py file:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "assets"),
os.path.join(BASE_DIR, "frontend/dist"),
]
# STATIC_ROOT = "" # The absolute path to the dir for collectstatic
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'dist/',
'STATS_FILE': os.path.join(BASE_DIR, 'frontend', 'webpack-stats.json'),
}
}
When I run the npm run build command I get notified that both the bundle.css and the bundle.js files have been generated:
File Size Gzipped
dist/bundle.js 150.73 KiB 51.05 KiB
dist/bundle.css 192.06 KiB 26.89 KiB
Images and other types of assets omitted.
DONE Build complete. The dist directory is ready to be deployed.
INFO Check out deployment instructions at https://cli.vuejs.org/guide/deployment.html
I really don't know why it is giving that ERR_CONNECTION_REFUSEDerror or how to fix it.
For production remove publicPath from your vue config file, I suppose you used that for development purposes, but in production you should only create the bundle and serve it to the user.
What's probably happening is that in your Docker setup you don't have the webpack dev server running (and you don't need it), thus you hit a connection refused error.
Note the code works perfectly fine when I'm running the code on my laptop.
The following two groups of code will run on my laptop. However the second group (which uses my custom package) doesn't work on Elastic Beanstalk running docker.
Standard Lib only
import (
"net/http"
"os"
)
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
http.ListenAndServe(":"+port, nil)
}
Uses Custom Package
import (
"os"
"github.com/sim/handlers"
)
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
handlers.ServeAndHandle(port) // wrapper of ListenAndServe
}
Error Messages:
Failed to build Docker image aws_beanstalk/staging-app: andlers: exit status 128 [0mtime="2015-08-14T05:08:17Z" level="info" msg="The command [/bin/sh -c go-wrapper download] returned a non-zero code: 1" . Check snapshot logs for details.
2015-08-14 01:08:15 UTC-0400 WARN Failed to build Docker image aws_beanstalk/staging-app, retrying...
cron.yaml
version: 1
cron:
- name: "task1"
url: "/scheduled"
schedule: "* * * * *"
You need a Dockerfile or/and Dockerrun.aws.json for your environment as per the documentation
Dockerfile
FROM FROM golang:1.3-onbuild
EXPOSE 3000
CMD ["go run <your.go.file>"]
Dockerrun.aws.json
{
"AWSEBDockerrunVersion": "1",
"Image": {
"Name": "golang:1.3-onbuild", # <-- don't need this if you are using a Dockerfile
"Update": "true"
},
"Ports": [
{
"ContainerPort": "3000"
}
],
"Logging": "/var/log/go"
}
Using the eb command line to deploy ?