#web-development
2 messages · Page 22 of 1
well
sigh.
this tutorial
you shouldnt be putting it in the code at all first off
can you link me to this
Hi
I'm deploying my site tomorrow
Can someone link me good tutorial how to deploy a flask app
dkh?
@midnight timber thank you.
Definitely will try it.@midnight timber
Are there any important prerequisites from Python I must be strong with? For django?
classes, inheritance, uhh, decorators? just OOP stuff really
@midnight timber ok
Django is "python"
it's very abstracted
it's better to think of it as an API that is written in python
and you interact with it via python
but you're actually learning Django's classes etc
@Aster Iris#696 thanks alot

@weak hazel also this https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django
is what I meant to link originally
@quaint ledge that tutorial is from 6 years ago
and even 6 years ago some of this was not a good practice
oh holy crap
using apache
yeah im sorry but virtually every aspect of this tutorial is not how things are done now
:/
the internet is great and terrible
you dont want to use apache, you dont want to be doing everything as sudo, you definitely dont want to be hard coding secret keys into the code
@vernal kraken it is pagination but I need to check if the URL is on that page in flask
does anyone have a good tutorial for deploying on digital ocean?
the one im using doesnt work
@quaint ledge you are asking the wrong question
hm what should i be asking
Install nginx on Ubuntu, install gunicorn into your python venv
Use the gunicorn docs to learn how to run the app with gunicorn
what
And then the gunicorn docs have a snippet for how to use it with nginx
I’ll find something straightforward to point you at when I’m at work
But the gunicorn docs are pretty solid for that
Other than that you’ll need to uninstall whatever Apache garbage because it’s probably currently using the same ports nginx will try to
alright, its relatively late for me so im probably going to be going to bed soon
Will help in a bit when I can but worse comes to worse, look for a tutorial that specifically is using nginx and gunicorn on Ubuntu that has been written in the last 3-4 years
ill try and see if i can get the vps wiped and start from a fresh plate tomorrow
okay
Did you try their own guide?
There they set it up with flask, uwsgi and nginx
Oh
The one @quaint ledge linked was one from 6 years ago using Apache and utilizing pretty poor practices
This one is also from 2015
i didnt see that when i searched for tutorials
https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uswgi-and-nginx-on-ubuntu-18-04
Ah this one is 2018
This might be getting into more esoteric debates but I have always preferred gunicorn
But
This looks far better still and should work
Shame they don’t clean up their own articles and such
Not sure even 6 years ago it was a good practice to everything with Sudo and to hard code your secret key in a python file you commit......
i think these articles are community posted
They source them
It’s how they got huge originally
They nabbed every tutorial
So that they’d come up in search results
And it worked very well
Anyways I’ll check that tutorial a bit later but is likely to be monumentally better
(If you’re remembering the other day when I was pushing a lot for more minimalist stuff like heroku... case in point haha)
Yup and once you have it you have it
should i be editing my files directly in the vps? ive just been using sftp to transfer the files i already made
It becomes a 5 minute thing you could do in your sleep in future projects. Assuming you don’t just have it automated and don’t have to do it at all
Umm
Do you not use git
i didnt think it was really worth the setup
Yeah that won’t be true for long
Either way
You can do whichever. Edit remotely or copy them, whatever is less annoying
Do not move the venv
Or any of the pyc / __pycache__ crap Python may spit out when you run it locally
Just copy your python files and recreate the venv in the server though I think you were already doing that
yea i am
im going to clear the server tomorrow though because the installs and everything is a mess
Haha yeah
I trash vms probably... 30-40 times a day
When you have one that works you can snapshot it
And then make new instances of it for new projects etc
okay
Is there any word on a python to wasm compiler? I'd love to use my existing classes for a PWA
...or better yet DOM and Component manipulation such as React/Vue in Python 😉
Hi. I've run into the realization that the thing I'm writing currently is best communicated with via a REST-like interface. I know it's possible to use Flask and Django and such to write those, and I've seen other things like FastAPI and Eve.
However, since my app is likely to just be local and ephemeral... I don't think I need the overhead of a full web app. Am I overthinking? Is the overhead not really that big?
if your app is totally local why do you feel you should use a rest like interface?
hello I'm running into a issue with some javscript I'm trying to add in a button and that button is not showing
javascript*
not sure why it wouldn't be showing up ?
well obviously because you're a develooper and not a developer
@eager portal if you don't have anything constructive to add to the conversation then don't say anything at all
@near ridge sorry won't happen again
Thank you
I've been trying to implement a way for the program to take an image file and to send it though the route /img/series/thumb/<path:url>/
I've tried to use a blueprint that uses series/ as a static folder but that comes back to bite me
Hello @leaden kindle Is this something your looking for ? https://www.youtube.com/watch?v=XeiOnkEI7XI
In React apps, you often have to upload images or files. Learn how easy it actually is to do that! Limited Offer! Join the Full React Course at 90% off: http...
This is sounds like what you're trying to do.
are you using react ?
Nope, Flask and Bootstrap
I'm trying to use an on-disk file
I think I might've found a work-in
what was you're solution ? I'm currently learning all of this
I'lls send you my project in a zip I guess
you could show it as a code snippet ?
Im looking to make a site that shows me an active member count of a Facebook community group. I plan to make a call to Facebooks Graph API to get a total user count of the group. Does this workflow make sense:
- Make API call to get member count and store that in a variable
- Use flask to render HTML code to display a counter with the # of members
is there a way you could show the code ? @leaden kindle ?
you can show the code this way THIS IS A TEST use
I'm still figuring it out
no problem 😃
do any one know about any alternative of "UserCreationForm" of django 1 in django 2
!ask
Asking good questions will yield a much higher chance of a quick response:
• Don't ask to ask your question, just go ahead and tell us your problem.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving
• Keep your patience while we're helping you.
You can find a much more detailed explanation on our website.
ugh nginx isnt workinnng
server blocks or something like that isnt working
are there any good really in depth tutorials for this stuff?
because i just dont know what im doing wrong
@quaint ledge Are you trying to set up a revese proxy with nginx?
It's where you map a domain name to a port and push the traffic to an IP/Port behind a firewall
I use it for easier managment of SSL
Here's my configurattion. It honestly probably has a lot of cruft (mostly to show images and style sheets when the site is down for reloads), but it's been serving a production flask app for over six months.
hm
( creating gist )
oh ok
too long to paste in chat, now that I look at it 😄
paste.pydis.com i think
ok
The biggest thing to watch for is the first 11 lines
the proxy_pass
client_max_body_size 3M;
server_name example.com;
location / {
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $http_host;
proxy_buffering off;
proxy_pass_header Server;
proxy_buffer_size 10k;
proxy_pass http://127.0.0.1:8000;
}
}``` is the meat of the config
this is all mine said to do
I use pm2 (normally used to manage nodejs sites) to keep gunicoron alive for the port 8000
It may not be the 'right way' to do it, but it's easy to script and manage
I start the app via the following command once pm2 is installed: pm2 start ./bin/pm2-example-server.sh --name "example.com web server"
pm2-example-server.sh looks like this:
ive had this server for three days and i havent been able to use because the tutorials are really hard to use
It takes time and practice
They way I did it may not be the way a veteran would do it, but the server that this app is running has node sites and a dotnet site running all managed through pm2
:/ how did you learn
I've been a sysop/sysdev for 20+ years. Reading and trial and error
Fatigue almost always brings hoplessness 😄
This looks more straight-forward than my multi-site soilution: https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-18-04
yea, im just frustrated after three days of nowhere
https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uswgi-and-nginx-on-ubuntu-18-04 im using this
but right now im just trying to setup nginx
its not working
Yep! I'm in the same boat with webassembly. I'm wanting to do too much with a technology that's still developing
what
im just wanting it to work
like do what it says in the tutorial
its not though
Step 5 is very important
it looks valid
but without running through it on a fresh server, I'm not sure if it's technically right
ugh im going to sleep, ill mess with it tomorrow
👍🏻
kinda been the same thing past three days
wake up, try to figure out the server, go to sleep
havent made any progress though
probably
i just dont have any way of telling what that is
these tutorials can be ambigious most of the time
thats why i just want something very verbose
Does everyone happen to know how to fix django login loads long. Sometimes it's fast and sometimes it just keeps loading, and when you press the login button again, it gives Forbidden error, but it logged me in. Weird :/
Hey guys, quick flask question. I'm creating a calculator and have all the form setup, what's the best way to display the result back into the page without redirecting to a results page
@elder brook Make like a is_hidden thing if you want to keep data in db
In Linux, fully deleted files are still stored until they have to be over-ridden
Not sure about windows or partially deleted in Linux
Hi!
Have any of you worked with Crossbar.io?
In general, which websocket library will you recommend, especially in terms of performance and load relability?
I don't know how to choose from the following libraries
https://flask-socketio.readthedocs.io
https://websockets.readthedocs.io
https://crossbar.io/docs
https://aiohttp.readthedocs.io
https://autobahn.readthedocs.io (with twisted and asyncio)
Thank you very much for your help!
not a programming question per say but does any1 have experience transferring domains out of hover? or in genreal
trying to transfer domain out of hover. got an email saying if you want to proceed with transfer, do nothing. but their support page says confirm it
does anyone have experience deploying on digital ocean?
ive been having trouble for the past few days trying to get it to work
It's just like deploying to any other linux machine
which i dont know
Uwsgi can be a bitch
i havent even gotten to that yet
Do you have error logs?
i dont know
How is it not working?
its not displaying the right thing, its hard to explain but basically server blocks arent working
Send me your config
im trying 1sec
Aight
okay, what config?
nginx
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
events {
worker_connections 768;
# multi_accept on;
}
http {
##
# Basic Settings
##
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# server_tokens off;
server_names_hash_bucket_size 64;
# server_name_in_redirect off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
##
# SSL Settings
##
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;
##
# Logging Settings
##
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
##
# Gzip Settings
##
gzip on;
# gzip_vary on;
# gzip_proxied any;
# gzip_comp_level 6;
# gzip_buffers 16 8k;
# gzip_http_version 1.1;
# gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
##
# Virtual Host Configs
##
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
#mail {
# # See sample authentication script at:
# # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
# # auth_http localhost/auth.php;
# # pop3_capabilities "TOP" "USER";
# # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
# server {
# listen localhost:110;
# protocol pop3;
# proxy on;
# }
#
# server {
# listen localhost:143;
# protocol imap;
# proxy on;
# }
#}
error log is empty
Can I get a ls of /etc/nginx/sites-enabled/?
ls -la /etc/nginx/sites-enabled/ perferable
heres this expect my website name is website.com (not really its something else but i censored it)total 8 drwxr-xr-x 2 root root 4096 Mar 28 12:25 . drwxr-xr-x 8 root root 4096 Mar 28 12:49 .. lrwxrwxrwx 1 root root 44 Mar 28 12:25 website.com -> /etc/nginx/sites-available/website.com lrwxrwxrwx 1 root root 34 Mar 28 09:00 default -> /etc/nginx/sites-available/default
Understandable
Can you cat both of them? feel free to censore the important bits
You can dm them to me if that makes you feel better
Sorry if this isn't the right spot for this. But I am trying to load a style.css file for my flask app.
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css')}}">
But it fails to load I keep getting ""GET /static/css/style.css HTTP/1.1" 404 -"
server {
listen 80;
listen [::]:80;
root /var/www/website.com/html;
index index.html index.htm index.nginx-debian.html;
server_name website.com www.website.com;
location / {
try_files $uri $uri/ =404;
}
}
thats for website.com
thats default
Are you using flask?
i dont have anything right now i just have an html file
i was told to do that
dont even have flask installed yet
Do you have an application to deploy?
wdym
Have you developed an application that you want to run on digital ocean?
yea i do
Is application wirtten using flask?
yep
nginx isnt working i dont think though
im doing the nginx setup right now
im on step 5
and its not displaying the index.html file
step five of the nginx setup*
hello?
hello
How do you guys manage data migrations testing in Django? I am currently using django-migration-testcase (https://github.com/plumdog/django_migration_testcase) but it is a pain to use for some reasons:
- migrations must be tested as a whole
- you cannot use factories (e.g. using
factoryboy) without redefining new factories every testcase because models change
@kindred cosmos do you know whats going on?
okay i found it out, it was some other files i had to edit
How would i setup a local to my network flask server? I'm trying to setup up a mock api i can use while developing a site at work, and I don't want to host it on the laptop im working on. I tried setting up a hotspot my 2 laptops connect together with, and use the same wifi. I run my flask app with --host = 0.0.0.0
Oh hey i got it to work
be on same network
app.run(..., host="0.0.0.0")
ipconfigon the computer thats hosting the app,
look for IPv4 address, connect to that (not 0.0.0.0) with port:5000unless changed
@covert marsh See if that gets it up for you
Wondering if anyone can help me? I am trying to load style.css file from static/css folder. Here is the what I have for code on the base.html.
{% extends 'bootstrap/base.html' %} {% block styles %} {{super()}} <link rel="stylesheet" href="{{ url_for('.static', filename='css/style.css')}}"> {% endblock %}
This is my folder structure
I keep getting this error though 127.0.0.1 - - [29/Mar/2019 09:26:07] "GET /static/css/style.css HTTP/1.1" 404 -
I tried adding it in just /static as well
Hi Everyone, I have what I hope is a simple, general question. I'm writing a web app using flask, and I already have Redis implemented for some simple storage. Is it possible/a secure idea to use Redis with Flask-Login?
@shy cradle why do you have your code as '.static' (why the . )?
I have a flask + angular app and my url_for function is just url_for('static', filename='path/to/file')
That is what the documentation has
I've tried it without as well
{% block styles %} {{super()}} <link rel="stylesheet" href="{{url_for('.static', filename='mystyle.css')}}"> {% endblock %}
what file is this in?
That is from the documentation https://pythonhosted.org/Flask-Bootstrap/basic-usage.html
It doesn't make any sense. The file is there.
hmm what OS are you running the server on?
macOS 10.14.3
I ask because I'm hosting mine on an ubuntu server and I've had issues with file permissions befire
before
Tried that as well chmod -R 777 static/css
Have you tried removing the period before static?
Static Files
Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called static in your package or next to your module and it will be available at /static on the application.
To generate URLs for static files, use the special 'static' endpoint name:
url_for('static', filename='style.css')
The file has to be stored on the filesystem as static/style.css.
Thats from the flask quickstart page
But I think that you can have subdirectories in the static directory still
ok, I moved the static folder up into the app folder and it appears to be working now or at least loading. Now to figure out how to do css properly.
Thanks for your help!
Have anyone in here worked with logging in from a server authentication (Ex. Firebase) and then retrieved data. In JS ofc.?
every time i open my chrome browser with selenium webdriver it shows data;,
has someone a solution
can someone help me?
Anyone here?
:D
Is return reverse('product:category:detail) possible?
3x colon? Ive been playing for an hr and got some url issues
Does everyone happen to know how to fix django login loads long. Sometimes it's fast and sometimes it just keeps loading, and when you press the login button again, it gives Forbidden error, but it logged me in. Weird :/
Hello,
I have created a dungeon generator in python that currently runs as a bot in discord (25s video showcasing it https://dungeonchannel.com/dungeons/other/DunGen_1.mp4). I would like to translate that to web, but honestly feel overwhelmed with the amount of information. I would like a single page app with a form (args) that would run the python script which would return an image to show. Basically something similar to this: https://donjon.bin.sh/fantasy/dungeon/ (clicking "random", as it'd be all in the same page) but modern-looking.
What would be the easiest way of achieving that?
From what I understand I would need to use something like Flask or Django to run the script, and React, Angular, Vue or similar to create the website. It feels like there would be a LOT to learn and I'd end up applying a minimal amount of that information to actually make this work. Are there any tutorials that focus on bringing something quickly to web that might help, or perhaps a sort of template I could use or follow?
Thank you!
I'm creating sections dynamically using an array passed into my Jinja2 templates.
I'm looping through this array using a for loop, and I would like to pass in some variables into a template and include it. Something like this:
{# inside 'sections.html' #}
{% for section in section_data %}
{% block title scoped %}{{ section.title }}{% endblock %}
{% block content scoped %}{{ section.content }}{% endblock %}
{% include 'section.html' %}
{% endfor %}
{# inside 'section.html' #}
<h2>{% block title %}{% endblock %}</h2>
<div>
{% block content %}{% endblock %}
</div>
In this code, however, the blocks aren't picked up by the include. I've looked through the Jinja2 documentation and on Google and I can't find anything to pass in blocks like this.
Thanks.
Fixed! 😃
flask?
hmm
Im having trouble using a login form from a different application
I am trying to use django all auth login form on a different template
So im trying to import the form in its views.py
class myCustomLoginForm(LoginForm):
def get_context_data(self, *args, **kwargs):
context=super(HomePage, self).get_context_data(*args, **kwargs)
context['login_form'] = LoginForm()
return context
doesnt seem to be working
I feel like you cant actually do that
Yea because django all auth
Probably forces you to login through accounts/login
Unless you had some crazy custom login form
I'm making an app in flask on a Vagrant machine. How should I configure everything so that I can view the output in a browser on my host machine?
is it possible to update my django app without taking down the website
!unmute 300363843685580810
:incoming_envelope: :ok_hand: Un-muted @native tide.
The filter hasn't been caught up to Discord allowing for multiple image attachments, you can send the images separately or using something like an imgur album
Django. @wraith shoal
It's not about it being more simpler it's more about it being more popular in the job industry.
That's great!!!
Personally I would recommend Django. 😃
Hey all,
Does anyone know if Flask cashes POST requests by default?
If I click a button a few times on my frontend, the chrome console looks like this:
I dont think its a JS issue
As the requests are making it to the server
and it being processed
POST requests should never be cached
Im just wondering why every other request seems to finish much faster
POST requests usally require some amount of processing time
This might mean your code is inefficient
Trivial doesn't mean it will proccess fast
@app.route("/test", methods=["POST"])
def test():
print("Request received")
return ""
Printing is slow
My question was more about why some requests seem to finish instantly when others seems to take 300ms+
Not that the code is running slow
😃
It depeneds on the code
On the flask side or JS side?
I don't have enough infomation to anwser that question
Well essentially, I have a button on my frontend which calls some JS which sends a post to the endpoint above
Every other click seems to finish stupidly fast for some reason
Almost as if something is being cached somewhere
Hope this makes sense
It depends on the code
It's normal for GET requests to be cached
To be cached by the browser
This is a POST, as defined in the JS as $.post()
This may be the wrong place to ask as it may be nothing to do with flask and have something to do with the browser instead
No I think this would be a fine place to ask
The issue is you aren't providing a lot of infomation to what's exactly is slow
I don't know what is slow
The issue isnt that something is slow
Im just wondering why some requests finish in 2ms
every other request*
Someone would have to look at the code to anwser that question
I couldn't tell you
Hey guys.
Anyone can help me with django and rest framework?
I need to make a groups of people to have acess to my website. I'm thinking, it's better create a group and put the users in this group and then next add permissions to that group.
Or not creat a group and add the permissions to the user
/w
?
@prisma pollen
@lavish prism
@web-development
idk where to start googling but i need some help with django
is there a way to use websockets on the client side??
How can I execute this assignment?
Can anyone help me or give some sources?
SQL Injection attacks and Cross -Site Scripting attacks are the two most common attacks on web application. Develop a new policy based Proxy Agent, which classifies the request as a scripted request or query based request, and then, detects the respective type of attack, if any in the request. It should detect both SQL injection attack as well as the Cross-Site Scripting attacks.
Hi everyone :D, I am just starting to get into coding / python (I am 14).
I am currently trying to make a full stack twitter clone with flask.
I would really appreciate some feedback. (Please don't hate I know the code is very messy and unorganized rn)
The link to my git repo is: https://github.com/nadav-ram/flask-tweeeter
Does anyone know how flask works with json and ajax?
is requests-futures the quickest and easiest way for sending requests quickly?
looking for ideas about how to mock server to server requests from a python web app to a remote service in development. My initial idea was to conditionally import requests_mock in dev so that the requets never leave the container and return data based on logic in those mocked routes
I'm fairly keen on some approach that is similar to what is done in frontend development where angular request mocking occurs and axios mocking is done so frontends don't have to wait around for backends to finish creating the api.
With flask-wtf, how do you get it to autosubmit once they press a radio button/unfocus from a select field?
Anyone how knows django rest framework to explain me some things i don't understannd in the tutorial?
hi i want to make a webeserwer on my rpi zero, i need just some simple API on it, so i know flask crys it should be used with some pro swerver like ngninx or soemthing but i dont think pi zero can handle it so any suggestion?
@native tide lead with the question
@glacial quartz if all you need is a simple webserver for an API, and you know flask, you have enough to roll with, you don't need nginx to run a flask app
@native tide you can start by hosting a hello world html using the http.server library in python 3
OH, @native tide is this the question from yesterday? (I just scrolled up)
Have you defined your groups properly? If you have the definition of your user journeys set out then it should be clear which is the solution you're looking for
If you have groups all sharing the same access-level, like members of a team all looking at the same assets, then the former
If "used by groups of people" is just a phrase you used, and they all need unique permissions, then it's the latter
@midnight timber : This too. I was looking for how create groups and sets permissions.
The permissions i can give with rest framework with the permissions.<permission> but i don't know how configure and create groups.
I not see anything in rest framework for this, so i guess i will have to create it with Django.
But im still lost. (Sorry bad english)
What's the best way to host Flask Applications?
Best or easiest? @thorn vapor? There are lots of very simple ways (Heroku) but they can get expensive.
The Heroku setup for python is available here: https://devcenter.heroku.com/articles/getting-started-with-python
It doesn't take long to get it to work.
@tardy pasture ty
No problem.
There are other very palatable options, depending on how SysAdminny you want to get.
ElasticBeanstalk on AWS is pretty good as well.
Heroku is probably the simplest.
But it may incur costs. It's been a while since I moved away from using Heroku, but they do constantly improve.
You could also just get a Linode and host there.
Nanode from Linode is $5 / mo. and works for a lot of personal projects.
Here's pricing for Heroku: https://devcenter.heroku.com/articles/usage-and-billing
If you can stay at the free level it's, well, free.
So that's nice.
Good option for beginners with personal projects.
more specifically,
- I have written a Python script on my Mac to help me track what I work on. The script writes the information to a publicly accessible spreadsheet.
- I converted the spreadsheet to a sqlite db via csv
- I have created a Flask app that is connected to this new db and it displays the info in html
Continuing on in my learning I need to figure out how to:
- I want to host this website somewhere publicly accessible
- I want my Python script to start writing to this database which is connected to the hosted Flask app instead of the spreadsheet
Based on this:
What do you think is the best hosting option for me to explore? Everything I have done so far in my learning has been local
Heroku sounds like it would work for you
my script (tool) looks like this:
and you could probably exist at Heroku for a while without incurring costs.
I'll read through this link you sent me in detail and try it out
I just PMed you this, but in case anyone else is reading, here's another Heroku link more about Flask: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xviii-deployment-on-heroku
@native tide Django has django.contrib.auth.models has a model for groups premade
conveniently it's named Group
is the documentation
it does exactly what you say you want
I'm guessing your serializer would add the member to the group in the rest_framework
What are examples of things you can do with Django that you can't do with Flask
i think evrything you can do with django you can do with flask
you can cut a tree with small axe or you can cut a tree with big axe, depedns on size of tree you cuting 😃
@midnight timber : Who add the member to the group is Django. Rest framework doesn't have management of groups, as far as i know.
The problem is how i will make the groups have the correct permissions
duno in django but in flask i use jwt
@glacial quartz WHAT
@native tide https://jwt.io/
@glacial quartz : so what
you can put in jwt clames/premissions
so user auths and you give him jwt with id="44" , rights="admin"
example
and when he sends request you know he is admin
Hi i need a book for web-dev i know only basic python.
duno what you trying to make but flask is an easy start
im trying to learn with tutorials on the net they are not explaining well so i dont understand so i thought if ill learn from a good book it will cover the most well
duno i dont like books at all 😃
from flask import Flask, request
APP = Flask(__name__)
@APP.route("/")
def hello():
return "Hello World!"
APP.debug = True
APP.run()
here simplest flask app, you can expand your knowlage form here i guess
how is he going to expand based on some random snippet? come on
hmm cuz he builds what he wants from here
duno i learn all stuff by needing doing it not by reading books
@coarse heath the tutorials that come with Flask or Django on their websites are both a good start
@glacial quartz that's just stupid, posting 5 lines to someone not done web dev before and saying "there you go, easy!"
at least point him to some existing tutorial
i think he allreayd knows how to google
i was just pointing out that flask in simplest form is a 5line code and probbaly easyer to get basics using it then going django
we probably just misunderstood each other. Flask is a good thing to start with, agreed
(as is Django 😄 )
@native tide then sorry i duno 😃
Trying to make a system where the user can create tags. I just want a text input field where upon submitting it it runs some client side to create an html element. Problem is I can't seem to find a way to do suppress sending POST/GETs from the form, and avoid refreshing the page
@tardy pasture I just went through the documentation you provided on Heroku and made notes on everything
really cool experience
👍
What do you include in a Procfile for a flask application
(basic testing / learning)
just trying to deploy something (anything)
(via Heroku)
Hi guys, Django question. I basically want to calculate the values of various products, but as each product type has a slightly calculation method and has different values used to compute it my current process is this. A selection form where the user selects the product type and an an attribute. The attribute is used to then narrow down rows in a database to provide further options for the customer to use for each calculation method - though the attribute is generally universal across all the calculation methods. Then depending on this initial selection it routes to specific views/templates designed for each calculation method (which includes a form)
I need to pass the attribute to each calculation method view
My problem is a) what's the best way to pass this data? b)is my whole workflow/process flawed
Hopefully that makes sense, I've been thinking about it for too long
@thorn vapor sorry I've been in meetings for hours. Glad you got it sorted!
@ashen anchor I'm not sure I'm following your workflow with products
@tardy pasture just figured out how to deploy something... was painful (for me) stuff wasn't workign as I tried to deploy an application I built yesterday. I made a very quick one today that returns some basic html to try it from scratch and got that to deploy.. a start
Alternatively, I can have one view which renders different forms based on the initial selection and then based on these calls different methods to be used for rendering the results
But I'm unsure on how to separate various post requests from eachother?
@tardy pasture Haha, okay I can see why you wouldn't, let me give an example
So, let's assume I sell paper rolls, paper sheets and paper bags. I want to know the weight of them per 1000 (whether that be 1000m, or 1000 sheets, 1000 bags). For a roll of paper I need the meterage and the width. For a sheet of paper I require the width and length of the sheet. For a bag I need the width and length of the bag. Now, there's not just one paper type, there's lots of different types each of which have different densities
So I have a model in the database with Material Type, Material Thickness and the Material Density
So what I mean is, firstly need to know which product type so I can know which fields to ask from the user, the available thicknesses for selection must then only be ones available in the database where the product type matches
Then finally I must get the density data, and perform a specific calculation before displaying the result to the user
Does that help clear it up a bit?
I'm basically thinking, store the product type and material type selection in the session or pass it in via url to the different calculation views
@coarse heath If you still are looking for a way to learn flask , I would recommend sentdex's flask tutorials (https://www.youtube.com/watch?v=Lv1fv-HmkQo&list=PLQVvvaa0QuDc_owjTbIY4rbgXOFkUYOUB) they really helped me understand flask
ok
I'm trying to deploy a little web application I made it has an SQLite database
(deploying to Heroku)
currently the file path of the db is a local path
how do i handle this when I deploy
@ionic ember This channel is for web development including django
Is there a specific django discord channel or separate server or does everyone just tend to use this one ?
Fo django questions etc..
@coarse heath django girls tutorial is probably recognised as the best starting tutorial. It starts completely from scratch, the django tutorial still assumes you know web dev things
My website is ugly - any tips on learning how to make it better looking?
Find websites you find pleasing and try to copy their template. Great way to learn styling
Through this process, you'll develop your own style. After all, every designer has someone or something they have been influenced by
Or, just stick with a template library (e.g. Google Materials, or Bootstrap)
Ok so I don't know what to do in this situation. Let me explain my problem:
So I'm currently using Python's Flask to open up a localhost server. This server is constantly updated with new information.
So now keep that in mind. I've made a site that allows users to watch for specific words (keywords I call them) in the server. Basically when a user hits the "Run" button on the site it starts all the tasks (which check the flask server for the specific keywords that the user put in). When a user clicks the Stop Task button, I need to stop the tasks (and stop watching the server)
So this is what I'm confused about:
What method should I use to access the server? Should I keep POSTing/GETing to the server with all the information that the user submitted (the keywords and stuff) or should I only do one POST/GET and do all the waiting/processing server sided?
Multiple people will be accessing the site at the same time
Dom, have you looked into websockets for real time updates?
I'll explain my whole scenario and then can you let me know if websockets would be helpful
So basically I'm using a discord bot to read messages and break it up. I then post it to my server
Then I have the whole thing that I explained in the text above
Gotcha. Maybe look into a messaging queue (e.g. celery or rq)
Well, actually might need both. so the websockets would be helpful for the "watching"
the queue would be if the discord bot takes awhile to process data (might not need it)
When a user hits "run" (open a websocket connection). When a user clicks stop (close the connection)
The "task running" part might be tricky depending on what you're trying to achieve
Since there's considerations of multiple threads , processes
That area is where celery/rq may help
👌
Hope that helps a bit. Its a lot of jargon if you're completely new to all of this
But it sounds like a very cool project, so good luck!
Rule of thumb is to never have any secure data in cookies. so in other words, fake away.
That being said, always have fail safes on the backend to check for alterations
has anyone taken this course?
https://www.udemy.com/rest-api-flask-and-python/?ranMID=39197&ranEAID=R7BSs79ua1Y&ranSiteID=R7BSs79ua1Y-Jo0d6lqgW36_2_hf17Bk7g&LSNPUBID=R7BSs79ua1Y
looking to potentially start this course as my first exposure to Flask
@fathom prism So Websockets is because a very long HTTP request right?
Would it be problematic if I have hundreds of users connecting and starting tasks on the site (aka connecting to the Flask server with hundreds of web socket connections? )
Also I'm going to be using herokuapp to host the flask server. Would that cause problems?
duno i plan to use ngnix and behind it flask servers if it has perfomace issue
websockets is not a http request.
anyway what websockets lib are you using? i saw there is flask-sockets thats 3 year old and flask-socketIO that has still updates but it has no nonjavascrip client form what i see
Thinking about Flask-socketIO
Grote I just think of it that its a way to send/recieve data from a server/site that stays open for a long time
Hi guys
I'm trying to upload a file through a form to Flask but no data seems to be transferred on the back end. The file is always empty. I have no clue what I'm doing wrong
How do I create a login system in django
Which allow only the one with password to access the next page
For now I'm doing
f = request.files['file']
f.save(secure_filename(f.filename))
The file name attribute is all fine on the front end. Is there any reason why nothing is being transferred?
@native tide i will try this https://github.com/aaugustin/websockets hope it work nice 😃
👌 Lemme know
So my HTML template has a CSS file called local-main.css
it also uses a image called dom.png
However whenever I go to my flask url
I get this info logged
127.0.0.1 - - [04/Apr/2019 08:51:07] "GET /local.css HTTP/1.1" 404 -
127.0.0.1 - - [04/Apr/2019 08:51:07] "GET /dom.png HTTP/1.1" 404 -```
Why is it 404?
@native tide I had a issue like this, my static folder existed outside of the app folder.
I don't have an app folder.
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__,template_folder="temps")
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
@app.route('/login')
def login():
return render_template('dalogin.html')
@app.route('/main')
def main():
return render_template('dom-main.html')
if __name__ == '__main__':
socketio.run(app)```
No static folder?
No AFAIK
what does the reference to the style sheet look like?
for example this is mine.
<link rel="stylesheet" href="{{url_for('static', filename='style.css')}}">
<link rel="stylesheet" type="text/css" href="local.css" />
I don't see the local.css file in your directory then
Flask Static Files - Learn Flask in simple and easy steps starting from basic to advanced concepts with examples including Overview, Environment, Application, Routing, Variable Rules, URL Building, HTTP Methods, Templates, Static Files, Request Object, Sending Form Data to Te...
try making a static folder and putting the .css file in there.
<script type = "text/javascript"
src = "{{ url_for('static', filename = 'hello.js') }}" ></script>```
like that but for CSS?
@shy cradle
Ya, that example is for javascript though. If you create a static folder and then use my example I think it should work.
<link rel="stylesheet" href="{{url_for('static', filename='style.css')}}">
kk
<link rel="stylesheet" href="{{url_for('static', filename='local.css')}}">
Ok it worked
but the images still don't come up

PythonAnywhere vs. Heroku vs. Google App Engine
GO!
selfhost ngnix + flask + whatewer 😃 , or instef flask aiohttp xD
@upbeat egret I followed this course:
https://www.udemy.com/python-and-flask-bootcamp-create-websites-using-flask
he explains a lot, and gives alot of examples, was my firsy Flask exposure too but it's really understandable
@native tide I have website on Flask_SocketIO like this : [ client <---> nginx (reverse proxy) <---> Gunicorn <---> Flask ]
but from a few hundred simultaneous connections, it crash
because Flask is based on WSGI and WSGI is synchronous
you have aiohttp, sanic, crossbar.io for do realtime in asynchronous application
aiohttp, sanic, are both based on asyncio
crossbar.io have librairie 'Autobahn python' that let you choose between twisted and asyncio
@neat cape what did you think of that course overall/honest opinion?
@upbeat egret I personally liked it, he talks about almost everything you need to know.
Mostly local tho so you won't really get into how to do it on a server but with a little bit of implementation that should be fine.
First you'll get a crash course about HTML and CSS, then he'll teach you the basics of python (functions, modules, syntax etc.)
After that he briefly explains how to setup your own virtual environments, basic routes, flask dynamic routing etc.
After that he teaches you the more advanced things like creating forms with flask/python, REST API's, SQL databases, OAuth and processing payments.
It also features a project where you create a social company blog.
I really enjoyed it personally and learned alot.
His voice is also not annoying to listen to and he speak very clearly
Hey everyone,
So i've been following a course on Udemy about using Flask to create web applications with Python.
But the entire course was focused on hosting it locally.
I've got my own little server and I really want to implement it there.
What is the best way to do this on my server?
For the virtual environment in the course he used Anaconda, is it recommended to use this on my server as well for this?
Hi all.
Sorry to post it without waiting for previous question answered.
Been trying to get some help for a good half of the day now =/
@neat cape nginx - uwsgi
what OS are you running ?
it doesn't take too long to get up and running (if you ignore certificate
hmm in aiohttp how do i get tottal number of websocket connections, and i want to have list of players so i need to bind to Player object that connection so when i want to example kick Player i can do it from Player
hmm i meybe think i got it
😃
So... can anyone help me with this issue I've posted?
i newer used django or pycharm so i cant
@woeful sphinx I'm running Ubuntu 18.04 on my server
@neat cape
then you google
uwsgi flask nginx
and a digitalocean tutorial is 99% guaranteed to pop up
found this:
https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uswgi-and-nginx-on-ubuntu-18-04
:p
o damn, it was excactly what you needed 😄
yup xD thank you very much!
@neat cape no problem
tell me if any trouble
pm
i will be online for a little while
so I've managed to get it up and running, and it is working exactly as I'd hoped.
just 1 thing, is it correct that I need to restart my entire server everytime I make a change?
So for example if I add a route to another page, will I need to restart my entire server or is there an easier way?
those are parameters
@native tide , http://flask.pocoo.org/docs/1.0/api/#flask.Request.args
Is it so you can get those values? bar and foo?
so what you care about is website.com/10 ?
That's not possible
It would be an invalid URL
Think of the URL as a folder directory
If you tried to go to C:/i-dont-exists it won't work
👍
People usually redirect to a 404 Not Found page
haha, no such thing needed. I do this because I like it
👍
any django experts awake?
!ask @rare oar
Asking good questions will yield a much higher chance of a quick response:
• Don't ask to ask your question, just go ahead and tell us your problem.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving
• Keep your patience while we're helping you.
You can find a much more detailed explanation on our website.
What's @rare oar
I wouldn't say I am an expert but I know a thing or two about django
hi, im having issues with my login on flask. i made a post on stackoverflow however ive been back and fourth with this guy since the 31st of march and i sort of really need help. here's a link to the post with all the specifics: https://stackoverflow.com/questions/55439038/issue-with-bytes-and-integers-in-python-while-working-with-flask-login thank you very much
(tbh i had no clue what the actual issue could be considered thats why the title sounds so stupid)
if you are like, able to help or anything please do tag me, as im going to be on/off discord 😃
Try return accounts.query.get(int(id.decode()))
I think I did give that a go but it won’t hurt to try again
str object has no attribute decode
Oh then return accounts.query.get(int(id)) should work
Show me the stack trace
sure, one moment
its too long to post on discord
https://pastebin.com/h8d3rEMy @kindred cosmos
hello fellas, im looking for some help with django REST framework, im playing around with filters using django-filters
Im having a problem though with returning more fields than the defualt fields in a get request. for example, replicating what this does in the python shell:
Product.objects.all().values('name', 'brand__name',)
@hexed linden before the return add print(id)
For some reason the str is a b"5"
I think something else in your stack is messed up
yeah, @kindred cosmos it prints b"5".
I also ran print(type(id)) and it returned str
do you need me to disclose the full source or something?
wouldn't be a big deal for me to do
Unfortunately I don't enough about flask to do anything about it
It looks like some where in your stack you are using str() where you need to be using .decode()
That's my best guess
How are you setting up your cookies?
I'm back
and I'm officially confused
So I decided I need to use websockets
but I have no idea how to integrate that into my Flask server
What module should i use
etc etc
@kindred cosmos wdym? and rip 😿
@hexed linden it looks like you called str on a bytes object instead of decode, that you should not do:
>>> str(b"foo")
"b'foo'"
@hexed linden because you have converted your bytes to str before, but using str
like in my example
i see
AC.move_to_element_with_offset(browser.find_element(By.XPATH, f'''//*[@onclick='javascript:pair("{pairingnum_for}","{pairingdate_for}",0,0,"",0,"CA")']'''), -75, 0).click()
AC.perform()```
I was referenced over here from the help section. With this code in python I get a StaleElementReferenceException after already having run similar code just prior. I understand the issue but every "fix" I have found on stackoverflow does not seem to work. I have tried loops with try/except.
I am using selenium to automate a webpage
WebDriverWait doesn't even wait 10 seconds. It just dumps the exception immediately.
I have this now
try:
WebDriverWait(browser, 10, ignored_exceptions=(StaleElementReferenceException)).until(EC.presence_of_element_located((By.XPATH, f'''//*[@onclick='javascript:pair("{pairingnum_for}","{pairingdate_for}",0,0,"",0,"CA")']''')))
AC.move_to_element_with_offset(browser.find_element(By.XPATH, f'''//*[@onclick='javascript:pair("{pairingnum_for}","{pairingdate_for}",0,0,"",0,"CA")']'''), -75, 0).click()
AC.perform()
break
except StaleElementReferenceException as e:
print('oops')
continue```
Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
return webbrowser.open(link)
Why does that return an Internal server error?
@hexed linden please link me source
@kindred cosmos https://pastebin.com/sWrQJWMD
@hexed linden line 237
its commented
i'm using UserMixin
actually... yes, it makes sense what you're saying
You did inherited it wrong
what would the solution be
Should class accounts(UserMixin, db.Model): not class accounts(db.Model, UserMixin):
Should be*
Mixins go first
Try that
File "d:\Programming\Python (Flask)\MRP UCP\env\lib\site-packages\flask_login\mixins.py", line 37, in get_id
return text_type(self.id)
AttributeError: 'accounts' object has no attribute 'id'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "d:\Programming\Python (Flask)\MRP UCP\env\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "d:\Programming\Python (Flask)\MRP UCP\env\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "d:\Programming\Python (Flask)\MRP UCP\env\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "d:\Programming\Python (Flask)\MRP UCP\env\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "d:\Programming\Python (Flask)\MRP UCP\env\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "d:\Programming\Python (Flask)\MRP UCP\env\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "D:\Programming\Python (Flask)\MRP UCP\app.py", line 93, in login
login_user(user)
File "d:\Programming\Python (Flask)\MRP UCP\env\lib\site-packages\flask_login\utils.py", line 161, in login_user
user_id = getattr(user, current_app.login_manager.id_attribute)()
File "d:\Programming\Python (Flask)\MRP UCP\env\lib\site-packages\flask_login\mixins.py", line 39, in get_id
raise NotImplementedError('No `id` attribute - override `get_id`')
NotImplementedError: No `id` attribute - override `get_id`
127.0.0.1 - - [05/Apr/2019 18:58:07] "POST /login HTTP/1.1" 500 -```
Oh you to make sure your ID variable is id not ID
my database has them as uppercase, don't know why :/
anyway, thank you so much, legend 🙏
No problem mang
Just update your stackoverflow post so that isn't lingering without an answer
@hexed linden
Cool
Anyone familiar with selenium? Trying to automate a webpage and I get StaleElementExceptions that really do not make sense to me.
driver.find_element(By.XPATH, 'path').click() ```
^^^This works with no issues after reloading the page.
```Python
AC.move_to_element(driver.find_element(By.XPATH, 'path')).click()
AC.perform()```
The above causes a StaleElementReferenceException. No idea why one works but the other does not. I would just use the first one but the link I need is 75 pixels left of the only element I could find to specifically identify the link. (no offset currently for troubleshooting purposes)
The code works the first time around but when I reload the page it will do the Stale Element Exception. I just have no idea why one method can find the element after a reload while the other one freaks out.
My brain is officially broken 😦
Yo there's definitely a chance I have something set up wrong, but when reviewing my logs, I see that Django Rest Framework is checking permissions for my view sets multiple times per request. Is that normal behavior? Because one of my permissions hits another API, and hitting it more than 1/s rate limits me (and is just inconsiderate of their API).
@native tide you might wanna show us your jinja.
hello i have a problem with my website when i press right arrow my website moves to the right how do i fix that ?
@native tide you'll need to mark it as safe to prevent that
{{ post.html | safe }}
just make sure you control that variable strictly, or you're exposing yourself to nasty security vulnerabilities
I have a cgi script that works fine when i run it on my windows computer but when i run it on my raspberry pi it creates a 403 error, does anyone know how to fix this?
any flask users
that can help
i am trying to generate one of my functions on my page and turn it to a recursive algorithm
is it it possible?
its a like button feature
@rough magnet Are you using nginx or apache?
Sorry
You can easily make a recursive function
You create your function then it would be called by your view
# imports and whatever
def recursive(index):
if index == 0:
return 6
return recursive(index -1) + 6
@app.route('/do')
def do(view):
a = recurvise(10)
return a
It would look something like that
@posts.route('/like/int:post_id/<action>')
@login_required
def like_action(post_id, action):
post = Post.query.filter_by(id=post_id).first_or_404()
if action == 'like':
current_user.like_post(post)
db.session.commit()
if action == 'unlike':
current_user.unlike_post(post)
db.session.commit()
return redirect(request.referrer)
this is what i have
@kindred cosmos
Use "```" at start and end for your code
It makes it easier to look at
Which function is your recursive function?
i don't know where to start that's the problem @kindred cosmos
i havent used these type of algorithms before
You're better off reading up on recursive functions then trying to use one if you never have you used them before
i have for like iteration functions
but it was with help with a book
i am trying to go from scratch with no help required from internet other than discord help
Why
In the sisutation a google search is better than anything I can do for you at this moment
If you have question or need some clairified I can help, but I am not about to walk you through how to make and use a recursive function
Hello, can anyone recommend me a Python web framework that can satisfy these features?
Id say flask would be better for that bc he is trying to do a simpler program
I also like flask better (I have used both)
@native tide
So I have managed to get my CGI scripts all running fine from my website, except that some of them need to be run with root permisions (they need to control neopixels from my raspberry pis GPIO pins)
is that something that is possible to do and if so how?
you don't
Hey guys, I have a dilemma , potentially
So I run a LAMP server right now with domain working
Site has no content though
However I am super comfortable with flask
Also I need to make an api, using flask and sql alchemy, this is super easy
Would it be wrong to run flask under one domain for the API and another domain(website content) with Apache (LAMP)
Same machine, it has good specs
itll be easier on the end user if you use a reverse proxy instead
also means you wont need multiple/wildcard ssl certs
Honestly not sure about using reverse proxy?
lets you map specific paths on a server to a whole other server
Ahh, ok
eg /static requests could all be forwarded to another server
Aka flask
ye
on apache
Ohh ok
on the main domain
https://httpd.apache.org/docs/2.4/howto/reverse_proxy.html has a little bit of info
Thank you
Hey so with reverse proxy, I think I do understand it. However I still have a question. So right now I have example.com with Apache working on domain... I’m creating API server with flask to access my DB information, so I would set the reverse proxy to example.com/api correct?
So example.com would still bring my content site up and I would use example.com/api as my api address to send get requests to flask
Hey
Someone here recommended me to use Websockets. The reason for this is because I need to keep checking my Flask server for new information that is put in. So how would that work? Would I keep polling for data and the requests show up in the network tab? Or is it different?
hey,
Is there any way of connecting flask to a db like mysql. Do I need to use the python library or does flask have some sort of way to do it?
thanks
i am trying to use aiohttp so my first issue is
@ROUTES.post('/auth')
async def auth_check(request):
data = {'some': 'data'}
return web.json_response(data)
if i dont send post to this /auth it respnds "405: Method Not Allowed" as plain text but i want it to respond as json, so how to tell it to do that ?
think i found it with midleware
@wheat trellis ikr man
@native tide you don’t
as they said.
you should use something that automatically generates a salt, like bcrypt
Sorry I have no idea what I said
flask being fun
Oh right
I think it’s great
I love things that can be broken down into their own little black boxes
No i haven't. My to learn list is already ginaormoys
Bottle is a micro framework like Flask
However it doesn’t have the cool extensions that flask does
they look so similar tbh
I need something to make a good api that I can host on aws lambda
Then I'm going to learn Vue for the frontend
JAM stacks baby. Javascript, APIs and Markup
Gl 😁
Much love for flask. Very flexible and it's quick enough for my webapp (now if I can only target my python functions and classes to wasm)
KeyError: '_apispec_request_data_name'
hmm but if somone dosent send data: { "somestuff":"2323232az" } i get a crash 500 interanl error
Im trying to work with django for a new project, and im wondering if there's any intuitive way to share models and a database between a django web server and another python program.
hi i am using aiohttp so from what i get i should try to use non blokcing awaits for stuff that thakes time, so now i need to hash my password i wanted to use argon2-cffi , it dosent have awiat by default , can i wrate it somehow or not?
you can use async stuff to push your hashing in to a different thread/process and then resume after its finished
generally by using a ProcessPoolExecutor, loop.run_in_executor and await asyncio.gather
however starting up a task in a process has a lot of overhead so it may not actually have any performance benefits for short, occasional tasks
Hi guys, does anyone know the proper way to multiprocess a flask app along side another function? My flask app accepts data through the web front end (via HTTP POST), puts it in a variable, and then a separate function is going to read from that variable and execute some other chain of events.
from flask import Flask
from multiprocessing import Process
from time import sleep
app = Flask(__name__)
queue = []
def queue_director(queue):
print("Starting queue_director")
while True:
num_pending_items = len(queue)
print("There are {} pending items in the queue".format(num_pending_items))
if num_pending_items > 0:
# launch another function to do 'stuff' based on each item in the queue until all items in the queue have been acted upon
sleep(5)
@app.route('/vlanchange/<vlan>/<speed>')
def accept_request(vlan, speed):
global queue
print("Received request: VLAN {0} to {1} Mbps".format(vlan, speed))
queue.append([vlan, speed])
print("queue is: {}".format(queue))
return 'Request to change VLAN {0} to {1} Mbps received\n'.format(vlan, speed)
if __name__ == '__main__':
try:
Process(target = app.run(debug=True)).start()
Process(target = queue_director(queue)).start()
except KeyboardInterrupt:
print("\nExiting by user request...\n")
quit()
The Process module is not starting both items in the try block. It starts the Flask app, and the only way to have it start my function queue_director is to Ctrl C out of Flask.
This is my first Flask app ever, so I don't even know if this is the best way to receive data from a client. A client will send a http post via cURL like so:
curl 127.0.0.1:5000/vlanchange/100/30
And the only thing I'm interested in is the <vlan> and <speed> variables. If you have any suggestions on a better way to accept data like this from a client, I'm all ears!
Am I unclear on what Flask can do? From what I'm seeing from various answers on Stack Overflow, it seems that Flask is for simple question/answer relationships between a client and a server. I am essentially trying to use Flask so it is the trigger for a larger program that will make configuration changes in my network.
@torpid terrace it looks like you are trying to do something like http://python-rq.org/ or http://www.celeryproject.org/ or https://huey.readthedocs.io/en/latest/
when trying to access a web page with requests lib by also providing valid user agent and proxies, it keeps returning code 500
although, in browser and also without proxies or user agents, it works just fine
The only thing i could find online is that it might be related to headers themselves, so i tried to naively copy paste headers from browser into my .py code and to no avail
Hey
I have a script where its ouput like:
"<p class="tidspunkt">{{buss['tid']}}</p>
<p class="linje">{{buss['linje']}}</p>
<p class="destinasjon">{{buss['destinasjon']}}</p>"
Then I have a .py where the data is entered. So I'm looking for a dropdown method that works with .py and outputs into the html
@wary talon thanks I'll take a look!
are all status codes under 201 fine?
or should i only continue when the status code is 200
201 is a success https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201
but unless you've created an item in an API or it just a web page, 200 is the better response code
okay so if response.status == 200 is preferred over if response.status <= 201 if im making an api call
all 2xx codes mean success
1xx is informational
2xx is sucess
3xx is redirection
4xx is client error
5xx is server error
anyone around to help with a gunicorn service file, i keep getting an error about it failing to load
finally figured it out
@wary talon it looks like Celery will do exactly what I need. Thanks again for pointing me in the right direction! Are you pretty good with it? I got the basic tasks for the beginning part of my new program down, but ran into problems when trying to pass an SSH session I created using Netmiko between tasks. I don’t have the specific error on hand, but it was something odd.
Hi. I'm trying to move from PHP to Python (in fact i'm refreshing my Python knowledge !) Do you know of any good big and clean project that i could study ?
Hey guys, can anyone help me with django rest framework?
I'm getting a problem when sending a variable that's is not serialible
to a request.session
@torpid terrace didn't use it for years, but I think for shared session you need to change worker type to Threaded, or open/close connection per worker
@quiet kite youtube has a lot of good resources
i'm struggling to figure this out we are using flask and my scrum master wants me to send data to a flask form but the data is independent of user input. Any links or ideas?
Has anyone here used Enom API?
@torpid terrace i dont know if you ever got an answer to this, but you are on the right track. you dont need to create a new process for flask, you can let it use your main process
however you should switch your queue over to the type provided by multiprocessing, a regular list isnt really safe for interprocess use.
you can have your queue_director block instead of using sleep as well. it will unblock and continue running once some other process puts data in to the queue
oh woops i just saw that you were suggested to use some other tech, my bad
i need to pass 2 variables from javascript to a flask form, any ideas?
you can make a hidden field that you use to store that data, just set it before its actually submitted
<input type="hidden">
@opal leaf how would i connect that to multiple options
im searching for books based on a keywork than i need to select a book and pass 2 variables conencted to it
i dont know javascript well enough to say the exact functions off the top of my head, but if you name the input then you can access it via the dom or jquery or whatever and set its value
for two variables, just have two hidden inputs with different names
the name/id will be the same thing that shows up on flask just like your regular inputs
Hey there, I have the following class:
class FollowForm(FlaskForm):
user = IntegerField()
follower = IntegerField()
submit = SubmitField("Follow")
and index.html:
<form method="POST" action="">
<div class="form-group">
{{ form.submit(class="btn btn-outline-info") }}
</div>
</form>
How can I auto input data so that I can send data without user inputing? Lets say I already have variables with values "user" and "follower" ready on the template.
user = IntegerField(default=123) ?
Haven't used Flask forms, but this might do the trick.
I want to send data from the form that is in html.
maybe something like "form.user = user"
You want to call a server side function without the submit?
form.submit() is already there.
Can you not define the action part to trigger something?
Or is that just a php thing?
This is my flask code:
@follow.route("/", methods=["GET", "POST"])
def follow():
form = FollowForm()
if form.is_submitted():
user = form.user.data
follower = form.user.data
pass
return render_template("index.html")
idk how to put form.user.data from html
without rendering fields user/follower in index.html
The reason why I want it like this is because I already have every information I need and do not need any input from the user.
Flask Sending Form Data to Template - Learn Flask in simple and easy steps starting from basic to advanced concepts with examples including Overview, Environment, Application, Routing, Variable Rules, URL Building, HTTP Methods, Templates, Static Files, Request Object, Sendin...
@limber hemlock
thks, I'll check it out
;D
@limber hemlock any luck, I need to do the same thing
Yes, I figured it out.
Glad you got it
you have to do the following:
<form method="POST" action="">
<div class="form-group">
{{ form.user(value=comment.author.id, type="hidden") }}
{{ form.follower(value=current_user.id, type="hidden")}}
{{ form.submit(class="btn btn-outline-info") }}
</div>
</form>
low i could kiss you if this works
hope it helps, its working for me ;D
i still need to figure out how to make it selectable. im loading in a list of books than i needa select one and have those options go to the form
Something like this? https://www.w3schools.com/html/tryit.asp?filename=tryhtml_elem_select
sadly thats only for dropdowns :/
anyone know if having a slug in the url has any affect on seo compared to having the arg as a get param
Why does that number after get, is so big?
It keeps getting bigger and bigger
Better picture
What is the size of MaglaVerde.png?
26,8 mb
Oh its bytes
Nvm
Thanks for saying that size thing.
So png is not good if you have lots of images
hi there, I got a bit of a dilemma and I'm not sure how to go around it. I have a bootstrap modal form on my homepage for both login and registering. obviously this becomes a bit problematic with flask as i cant seem to find any way of differentiating between them two. i tried printing out my email field (this only shows in registration) in a try except statement however this still produced a error 400 for the user, so this is not a viable option for me. in terms of printing out error messages, ive already set up message flashing so i should be alright. hope you can help, thanks 😄
I didn't get what you mean. I'm still pretty baffled but I got somewhere closer to a solution
do you see how you can specify method in HTML?
well, I was wondering if POST2 is possible, lmfaooo. sounds dumb as fuck tbh
yep no never mind
I'm gonna split up my login and register instead.
Can someone help me with a simple SQLAlchemy query
I've been stuck on it for hours.. I have tried every possible thing I can
Seems like a simple Syntax error I am making, but I'm still too dumb to know what it is. Seriously tried every thing I could think of
"relation <tablename> does not exist", have you initialized your database? i have not used sqlachemy but with sql you need to execute some create table commands to build a table before you can use a database. you might see what you need to do to make sqlachemy build your database
Does anyone knows a tutorial to connect gmail using ssl and communicate using pop3 protocol that you created?
Hello, i have build a flask/sqlcalchemy/marshmallow api, and i want to build a django web app. How do i go about integrating the two?
@thick light what do you mean?
@deep narwhal there are plenty, just google it, you'll find them in seconds
@thick light nah just tell your issues here
if I can't answer someone else might be able to
didn't want to spam
that is not spam, it is the whole point of this discord
so bascially, i built an api using flask/sqlalchemy and marshmallow
and i built a django web app
i want to get the json data from the api so i can use it inside my web app, but i didn't quite understand how to
@unborn terrace they use the pop library
@deep narwhal yeah, so what is the issue? https://docs.python.org/3/library/poplib.html
Why?
I have a flask run from cli with click. I want to the arguments passed on on to click.options to be accessable in the flask server. What is a smart way of doing this?
Hey there, I have updated my User class with a new column for sqlite. How do I recreate/update my db with the new column?
I tried below but my db wont update.
from yourapp import db, create_app
db.create_all(app=create_app())
@native tide load them into your configuration system or something like that
@unborn terrace university work
@deep narwhal well, you got everything you need here https://www.ietf.org/rfc/rfc1939.txt
Checkout the Wikipedia article for some overview
Yeah i need to use that
Also this for an explained example http://www.eventhelix.com/RealtimeMantra/Networking/POP3.pdf
Good luck, implementing existing protocols is tedious af, that's why nobody does that in real life
(well POP3 is not the worse, that's that)
I tried using c
So i was searching of how to communicate with with the gmail site
I know you need ssl
But c doesn't i lib for that
So I'm trying to use in python
C has libs for pretty much everything, as most languages
@unborn terrace Thanks for pointing me to the right track. This seems pretty good way to approach it. I tried flask g for an example and just didn't seem to get it to work and having an endpoint with the needed data seemed hacky.
when working with aiohttp do i have to wrap evry function with async/await, i have some just pure logic functions that dont think take 0.0001sec
and anyone have an example of aiohttp with Gino ?
so, there is a simple rule if you function needs to use await then it should be async itself
there is no benefit in wrapping a pure function into async
e.g you can do something like that
async def fetch_numbers(...):
return await some_http_call()
def sum(a,b):
return a + b
async def main():
a,b = await fetch_numbers()
return sum(a,b)
loop = get_event_loop()
loop.run_until_complete(main)
so as long as your function is not a blocking function you can easily mix it with async functions
thats what i thinked too jsut wanted somone to confirm 😃 , now only thing left is to figure out what to do for DB if using aiohttp, i head flask app that runed np but cant figure out how to run this gino thingy am thinking of just doing pure SQL with asyncpg or something, i cant figure out they all put examples with main() and connect, i thinked my app should not dissconect connect evry times it needs request or am i worng?
@native tide flask starts to search for folders inside the same directory
-somefolder
-app.py
-public```
So it should be like this
If it is like this any you still get the error
I probably need to take a look at the whole project
What is the url generated for your statics? @native tide
style-attibute: myvalue !important
P sure important inside template can't be overridden by stylesheet
Don't know that much css
But I think you wrote them per tag and class
It would be ridiculous to write a case for a div tag and have every item in it to inherit the same attributes
Probably there is a better way but I don't know how
Apparently there are some properties that are automatically inherited
And there are some that aren't automatic
font-size is inherited automatically for instance
why would / be showing the index.html page?
<article class="message is-dark" style="width:500px; display: inline;">
you'd ideally want to use a non-fixed width though
@bronze ermine
np
some webservers do that by default and it's more or less convention but usually that won't be done automatically
I need to write a query where I take filtered list of IDs from one table and filter the results with another table. sqlachemy
Can any1 give me an example how it would look like?
Hey
does anyone know how to setup automatic db failover on Django
So lets say for example I had two db hosts proxy1.db.com and proxy2.db.com that connect to the same MySQL clusters. But proxy1.db.com was to fail - how can I set it so it will start using proxy2.db.com?
I've downloaded a bootstrap template and want to load it up with a flask web app. Do all those files and folders need to be in the same directory as my flask.py or can I put them in a subdirectory?
how do you do footers in flask? i've spent an embarrisingly long time trying to figure it out
@limber orchid , no you can add them anywhere you’d like. They’re also irrespective of flask meaning they only interact with your HTML pages.
@upbeat egret how do you mean footers? Are you referring to templates in flask jinja?
Hey how do I make a section clickable/transport you to another link? (in html)
@ me if you know so I get a notification please
Thanks
@fathom prism im referring to footers - its quite easy to implement navbars (which go in every page) in a base.html page - but im unsure of how to do it for footers?