#web-development

2 messages · Page 22 of 1

quaint ledge
#

is this the only place i use it?

junior cloak
#

well

#

sigh.

#

this tutorial

#

you shouldnt be putting it in the code at all first off

#

can you link me to this

quaint ledge
vagrant adder
#

Hi

#

I'm deploying my site tomorrow

#

Can someone link me good tutorial how to deploy a flask app

quaint ledge
#

dkh?

weak hazel
#

@midnight timber thank you.

midnight timber
#

it's for a rest framework

#

but it introduces the concepts really well

weak hazel
#

Definitely will try it.@midnight timber

#

Are there any important prerequisites from Python I must be strong with? For django?

midnight timber
#

classes, inheritance, uhh, decorators? just OOP stuff really

weak hazel
#

@midnight timber ok

midnight timber
#

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

weak hazel
#

@Aster Iris#696 thanks alot

midnight timber
#

is what I meant to link originally

junior cloak
#

@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

quaint ledge
#

:/

#

idk what to do, my code isnt working either, im taking a break rn

steel tiger
#

@vernal kraken it is pagination but I need to check if the URL is on that page in flask

quaint ledge
#

does anyone have a good tutorial for deploying on digital ocean?

#

the one im using doesnt work

junior cloak
#

@quaint ledge you are asking the wrong question

quaint ledge
#

hm what should i be asking

junior cloak
#

Install nginx on Ubuntu, install gunicorn into your python venv

#

Use the gunicorn docs to learn how to run the app with gunicorn

quaint ledge
#

what

junior cloak
#

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

quaint ledge
#

alright, its relatively late for me so im probably going to be going to bed soon

junior cloak
#

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

quaint ledge
#

ill try and see if i can get the vps wiped and start from a fresh plate tomorrow

junior cloak
#

DO has nothing to do with it

#

Don’t try to find anything specific to them

quaint ledge
#

okay

quiet solstice
#

Did you try their own guide?

junior cloak
#

Haha

#

Look above at the link

#

It’s so frustrating

quiet solstice
#

There they set it up with flask, uwsgi and nginx

junior cloak
#

Oh

quiet solstice
junior cloak
#

The one @quaint ledge linked was one from 6 years ago using Apache and utilizing pretty poor practices

quiet solstice
#

This one is also from 2015

quaint ledge
#

i didnt see that when i searched for tutorials

quiet solstice
junior cloak
#

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......

quaint ledge
#

i think these articles are community posted

junior cloak
#

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)

quaint ledge
#

ill check it out tomorrow

#

yea i see that now :o

#

but i feel closer every step

junior cloak
#

Yup and once you have it you have it

quaint ledge
#

should i be editing my files directly in the vps? ive just been using sftp to transfer the files i already made

junior cloak
#

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

quaint ledge
#

i didnt think it was really worth the setup

junior cloak
#

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

quaint ledge
#

yea i am

junior cloak
#

I never put anything on a server until it works perfectly locally

#

Okay cool

quaint ledge
#

im going to clear the server tomorrow though because the installs and everything is a mess

junior cloak
#

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

quaint ledge
#

okay

surreal kayak
#

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 😉

paper jewel
#

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?

opal leaf
#

if your app is totally local why do you feel you should use a rest like interface?

fair pumice
#

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 ?

eager portal
#

well obviously because you're a develooper and not a developer

near ridge
#

@eager portal if you don't have anything constructive to add to the conversation then don't say anything at all

eager portal
#

@near ridge sorry won't happen again

near ridge
#

Thank you

leaden kindle
#

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

fair pumice
#

This is sounds like what you're trying to do.

#

are you using react ?

leaden kindle
#

Nope, Flask and Bootstrap

#

I'm trying to use an on-disk file

#

I think I might've found a work-in

fair pumice
#

what was you're solution ? I'm currently learning all of this

leaden kindle
#

I'lls send you my project in a zip I guess

fair pumice
#

you could show it as a code snippet ?

leaden kindle
#

It's not really working

#

uh yeah

pastel dove
#

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:

  1. Make API call to get member count and store that in a variable
  2. Use flask to render HTML code to display a counter with the # of members
fair pumice
#

is there a way you could show the code ? @leaden kindle ?

#

you can show the code this way THIS IS A TEST use

leaden kindle
#

I'm still figuring it out

fair pumice
#

no problem 😃

uneven garden
#

do any one know about any alternative of "UserCreationForm" of django 1 in django 2

native tide
#

Hey

#

anyone here how uses django can help me?

quaint ledge
#

!ask

lavish prismBOT
#
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.

quaint ledge
#

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

surreal kayak
#

@quaint ledge Are you trying to set up a revese proxy with nginx?

quaint ledge
#

i dont think so

#

not sure what that is

surreal kayak
#

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

quaint ledge
#

yes

#

i am i think

surreal kayak
#

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.

quaint ledge
#

hm

surreal kayak
#

( creating gist )

quaint ledge
#

oh ok

surreal kayak
#

too long to paste in chat, now that I look at it 😄

quaint ledge
surreal kayak
quaint ledge
#

ok

surreal kayak
#

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
quaint ledge
surreal kayak
#

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"

quaint ledge
#

dont know what any of that is

#

ugh these tutorials are so confusing

surreal kayak
#

sorry had other stuff in that paste

quaint ledge
#

ive had this server for three days and i havent been able to use because the tutorials are really hard to use

surreal kayak
#

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

quaint ledge
#

:/ how did you learn

surreal kayak
#

I've been a sysop/sysdev for 20+ years. Reading and trial and error

quaint ledge
#

ugh

#

:(

#

i have no idea what to do though

#

and im tired, its late

surreal kayak
#

Fatigue almost always brings hoplessness 😄

#
DigitalOcean

In this guide, you will build a Python application using the Flask microframework on Ubuntu 18.04. The bulk of this article will be about how to set up the Gunicorn application server and how to launch the application and configure Nginx to act as a f

quaint ledge
#

yea, im just frustrated after three days of nowhere

#

but right now im just trying to setup nginx

#

its not working

surreal kayak
#

Yep! I'm in the same boat with webassembly. I'm wanting to do too much with a technology that's still developing

quaint ledge
#

what

#

im just wanting it to work

#

like do what it says in the tutorial

#

its not though

surreal kayak
#

Step 5 is very important

quaint ledge
#

which is what im stuck on

#

not working, ive done everything theyve said

surreal kayak
#

it looks valid

#

but without running through it on a fresh server, I'm not sure if it's technically right

quaint ledge
#

ugh im going to sleep, ill mess with it tomorrow

surreal kayak
#

👍🏻

quaint ledge
#

kinda been the same thing past three days

#

wake up, try to figure out the server, go to sleep

#

havent made any progress though

surreal kayak
#

I bet it's something small

#

( it almost always is )

quaint ledge
#

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

elder nebula
#

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 :/

ashen anchor
#

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

steel tiger
#

@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

meager helm
#

Thank you very much for your help!

odd swallow
#

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

quaint ledge
#

does anyone have experience deploying on digital ocean?

#

ive been having trouble for the past few days trying to get it to work

kindred cosmos
#

It's just like deploying to any other linux machine

quaint ledge
#

which i dont know

kindred cosmos
#

What are you using nginx? apache?

#

Uwsgi?

quaint ledge
#

nginx

#

and uwsgi

#

nginx isnt working

kindred cosmos
#

Uwsgi can be a bitch

quaint ledge
#

i havent even gotten to that yet

kindred cosmos
#

Do you have error logs?

quaint ledge
#

i dont know

kindred cosmos
#

How is it not working?

quaint ledge
#

its not displaying the right thing, its hard to explain but basically server blocks arent working

kindred cosmos
#

Send me your config

quaint ledge
#

im trying 1sec

kindred cosmos
#

Aight

quaint ledge
#

okay, what config?

kindred cosmos
#

nginx

quaint ledge
#
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

kindred cosmos
#

Can I get a ls of /etc/nginx/sites-enabled/?

#

ls -la /etc/nginx/sites-enabled/ perferable

quaint ledge
#

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

kindred cosmos
#

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

shy cradle
#

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 -"

quaint ledge
#
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 default

kindred cosmos
#

Are you using flask?

quaint ledge
#

i dont have anything right now i just have an html file

#

i was told to do that

#

dont even have flask installed yet

kindred cosmos
#

Do you have an application to deploy?

quaint ledge
#

wdym

kindred cosmos
#

Have you developed an application that you want to run on digital ocean?

quaint ledge
#

yea i do

kindred cosmos
#

Is application wirtten using flask?

quaint ledge
#

yes

#

and html and css*

kindred cosmos
quaint ledge
#

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?

soft pebble
#

hello

unborn terrace
#

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
quaint ledge
#

@kindred cosmos do you know whats going on?

quaint ledge
#

okay i found it out, it was some other files i had to edit

olive wharf
#

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")
ipconfig on the computer thats hosting the app,
look for IPv4 address, connect to that (not 0.0.0.0) with port :5000 unless changed
@covert marsh See if that gets it up for you

shy cradle
#

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

lofty sleet
#

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')

shy cradle
#

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 %}

lofty sleet
#

what file is this in?

shy cradle
#

It doesn't make any sense. The file is there.

lofty sleet
#

hmm what OS are you running the server on?

shy cradle
#

macOS 10.14.3

lofty sleet
#

I ask because I'm hosting mine on an ubuntu server and I've had issues with file permissions befire

#

before

shy cradle
#

Tried that as well chmod -R 777 static/css

lofty sleet
#

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

shy cradle
#

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.

lofty sleet
#

Nice! Good luck with the CSS, it can be a real pain hah

#

a

shy cradle
#

Thanks for your help!

frank karma
#

Have anyone in here worked with logging in from a server authentication (Ex. Firebase) and then retrieved data. In JS ofc.?

deep mason
#

every time i open my chrome browser with selenium webdriver it shows data;,

#

has someone a solution

#

can someone help me?

austere apex
#

Anyone here?

#

:D

#

Is return reverse('product:category:detail) possible?

#

3x colon? Ive been playing for an hr and got some url issues

elder nebula
#

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 :/

split copper
#

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!

trim kiln
#

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.

native tide
#

Fixed! 😃

radiant river
#

Im trying to use a form from another app

#

In a different app

#

Is this possible

native tide
#

yeah

#

google that

#

You just import the app

native tide
#

Hey, anyone here know rest framework and can help me with serials relationship

#

?

vagrant adder
#

flask?

radiant river
#

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

radiant river
#

Unless you had some crazy custom login form

primal grove
#

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?

sacred oasis
#

is it possible to update my django app without taking down the website

native tide
#

Hey, anyone who know django rest to help mew

#

?

keen plume
#

!unmute 300363843685580810

lavish prismBOT
#

:incoming_envelope: :ok_hand: Un-muted @native tide.

keen plume
#

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

wraith shoal
#

Hi guys

#

Starting with web development

#

Should I learn flask or Django

native tide
#

Django. @wraith shoal

wraith shoal
#

👍

#

I have heard flask is more simpler

native tide
#

It's not about it being more simpler it's more about it being more popular in the job industry.

wraith shoal
#

That's great!!!

native tide
#

Personally I would recommend Django. 😃

rapid aspen
#

I dont think its a JS issue

#

As the requests are making it to the server

#

and it being processed

kindred cosmos
#

POST requests should never be cached

rapid aspen
#

Im just wondering why every other request seems to finish much faster

kindred cosmos
#

POST requests usally require some amount of processing time

#

This might mean your code is inefficient

rapid aspen
#

Well I mean

#

The code on the server is trivial

kindred cosmos
#

Trivial doesn't mean it will proccess fast

rapid aspen
#
@app.route("/test", methods=["POST"])
def test():
    print("Request received")
    return ""
kindred cosmos
#

Printing is slow

rapid aspen
#

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

#

😃

kindred cosmos
#

It depeneds on the code

rapid aspen
#

On the flask side or JS side?

kindred cosmos
#

I don't have enough infomation to anwser that question

rapid aspen
#

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

kindred cosmos
#

It depends on the code

#

It's normal for GET requests to be cached

#

To be cached by the browser

rapid aspen
#

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

kindred cosmos
#

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

rapid aspen
#

The issue isnt that something is slow

#

Im just wondering why some requests finish in 2ms

#

every other request*

kindred cosmos
#

Someone would have to look at the code to anwser that question

#

I couldn't tell you

rapid aspen
#

Ok no worries

#

😃

ripe pecan
#

It could be just randomness

#

have you run multiple trials and averaged the time

native tide
#

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

rough jasper
#

idk where to start googling but i need some help with django
is there a way to use websockets on the client side??

rose imp
#

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.

barren path
#

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

rich panther
#

Does anyone know how flask works with json and ajax?

arctic mist
#

is requests-futures the quickest and easiest way for sending requests quickly?

gaunt torrent
#

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.

steel tiger
#

With flask-wtf, how do you get it to autosubmit once they press a radio button/unfocus from a select field?

native tide
#

Anyone how knows django rest framework to explain me some things i don't understannd in the tutorial?

glacial quartz
#

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
#

Hoe i make a website

#

How

midnight timber
#

@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

native tide
#

@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)

thorn vapor
#

What's the best way to host Flask Applications?

tardy pasture
#

Best or easiest? @thorn vapor? There are lots of very simple ways (Heroku) but they can get expensive.

#

It doesn't take long to get it to work.

thorn vapor
#

@tardy pasture ty

tardy pasture
#

No problem.

#

There are other very palatable options, depending on how SysAdminny you want to get.

#

ElasticBeanstalk on AWS is pretty good as well.

thorn vapor
#

I'm new

#

learning

tardy pasture
#

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.

#

If you can stay at the free level it's, well, free.

#

So that's nice.

#

Good option for beginners with personal projects.

thorn vapor
#

more specifically,

  1. 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.
  2. I converted the spreadsheet to a sqlite db via csv
  3. 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:

  1. I want to host this website somewhere publicly accessible
  2. 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

tardy pasture
#

Heroku sounds like it would work for you

thorn vapor
tardy pasture
#

and you could probably exist at Heroku for a while without incurring costs.

thorn vapor
#

I'll read through this link you sent me in detail and try it out

tardy pasture
midnight timber
#

@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

thorn vapor
#

What are examples of things you can do with Django that you can't do with Flask

glacial quartz
#

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 😃

native tide
#

@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

glacial quartz
#

duno in django but in flask i use jwt

native tide
#

@glacial quartz WHAT

glacial quartz
#

@native tide https://jwt.io/

JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.

native tide
#

@glacial quartz : so what

glacial quartz
#

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

coarse heath
#

Hi i need a book for web-dev i know only basic python.

glacial quartz
#

duno what you trying to make but flask is an easy start

coarse heath
#

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

glacial quartz
#

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

shrewd bluff
#

how is he going to expand based on some random snippet? come on

glacial quartz
#

hmm cuz he builds what he wants from here

#

duno i learn all stuff by needing doing it not by reading books

shrewd bluff
#

@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

glacial quartz
#

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

shrewd bluff
#

we probably just misunderstood each other. Flask is a good thing to start with, agreed

#

(as is Django 😄 )

native tide
#

Rest already have a permissions conf

#

i don't need use anything else

glacial quartz
#

@native tide then sorry i duno 😃

round egret
#

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

thorn vapor
#

@tardy pasture I just went through the documentation you provided on Heroku and made notes on everything

#

really cool experience

tardy pasture
#

👍

thorn vapor
#

What do you include in a Procfile for a flask application

#

(basic testing / learning)

#

just trying to deploy something (anything)

#

(via Heroku)

thorn vapor
#

disregard

#

sorted this out

ashen anchor
#

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

tardy pasture
#

@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

thorn vapor
#

@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

ashen anchor
#

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

orchid aspen
thorn vapor
#

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

olive wharf
#

@ionic ember This channel is for web development including django

swift trout
#

Is there a specific django discord channel or separate server or does everyone just tend to use this one ?

#

Fo django questions etc..

swift trout
#

@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

hallow ferry
#

My website is ugly - any tips on learning how to make it better looking?

fathom prism
#

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)

native tide
#

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

fathom prism
#

Dom, have you looked into websockets for real time updates?

native tide
#

No not really

#

What is that?

fathom prism
#

Think of it like keeping a connection always open

#

I recommend reading up on it

native tide
#

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

fathom prism
#

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

native tide
#

👌

fathom prism
#

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!

fathom prism
#

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

upbeat egret
#

looking to potentially start this course as my first exposure to Flask

native tide
#

@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?

glacial quartz
#

duno i plan to use ngnix and behind it flask servers if it has perfomace issue

quiet solstice
#

websockets is not a http request.

glacial quartz
#

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

native tide
#

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

wraith shoal
#

Hi guys

queen hound
#

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

wraith shoal
#

How do I create a login system in django

#

Which allow only the one with password to access the next page

queen hound
#

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?

glacial quartz
native tide
#

👌 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?

shy cradle
#

@native tide I had a issue like this, my static folder existed outside of the app folder.

native tide
#

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)```
shy cradle
#

No static folder?

native tide
#

No AFAIK

shy cradle
#

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')}}">

native tide
#

<link rel="stylesheet" type="text/css" href="local.css" />

shy cradle
#

I don't see the local.css file in your directory then

native tide
#

Yea i noticed that and put it in

#

still nada

shy cradle
#

try making a static folder and putting the .css file in there.

native tide
#
 <script type = "text/javascript" 
         src = "{{ url_for('static', filename = 'hello.js') }}" ></script>```
#

like that but for CSS?

#

@shy cradle

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')}}">

native tide
#

kk

#
  <link rel="stylesheet" href="{{url_for('static', filename='local.css')}}">
#

Ok it worked

#

but the images still don't come up

barren path
#

PythonAnywhere vs. Heroku vs. Google App Engine
GO!

glacial quartz
#

selfhost ngnix + flask + whatewer 😃 , or instef flask aiohttp xD

neat cape
meager helm
#

@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

native tide
#

So whats the best way?

#

I might have upto 500 ppl

meager helm
#

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

upbeat egret
#

@neat cape what did you think of that course overall/honest opinion?

neat cape
#

@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

neat cape
#

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?

frigid egret
#

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 =/

woeful sphinx
#

@neat cape nginx - uwsgi

#

what OS are you running ?

#

it doesn't take too long to get up and running (if you ignore certificate

glacial quartz
#

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

#

😃

frigid egret
#

So... can anyone help me with this issue I've posted?

glacial quartz
#

i newer used django or pycharm so i cant

neat cape
#

@woeful sphinx I'm running Ubuntu 18.04 on my server

woeful sphinx
#

@neat cape

#

then you google

#

uwsgi flask nginx

#

and a digitalocean tutorial is 99% guaranteed to pop up

neat cape
woeful sphinx
#

o damn, it was excactly what you needed 😄

neat cape
#

yup xD thank you very much!

woeful sphinx
#

@neat cape no problem

#

tell me if any trouble

#

pm

#

i will be online for a little while

neat cape
#

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?

honest flame
#

how to remove teh

#

the* lines

mystic pagoda
#

blame your ide

honest flame
#

ins ublime text

#

sublime text isn't ide

fathom prism
#

those are parameters

#

Is it so you can get those values? bar and foo?

#

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

#

👍

rare oar
#

any django experts awake?

unborn terrace
#

!ask @rare oar

lavish prismBOT
#
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.

kindred cosmos
#

What's @rare oar

#

I wouldn't say I am an expert but I know a thing or two about django

hexed linden
#

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 😃

kindred cosmos
#

Try return accounts.query.get(int(id.decode()))

hexed linden
#

I think I did give that a go but it won’t hurt to try again

#

str object has no attribute decode

kindred cosmos
#

Oh then return accounts.query.get(int(id)) should work

hexed linden
#

Tried that

#

Gave me some invalid literal with base 10 error

kindred cosmos
#

Show me the stack trace

hexed linden
#

sure, one moment

#

its too long to post on discord

livid wagon
#

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',)
kindred cosmos
#

@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

hexed linden
#

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

kindred cosmos
#

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?

native tide
#

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

hexed linden
#

@kindred cosmos wdym? and rip 😿

unborn terrace
#

@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
#

it said that .decode() couldn't be ran

#

no?

unborn terrace
#

@hexed linden because you have converted your bytes to str before, but using str

#

like in my example

hexed linden
#

i see

terse shore
#

            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```
native tide
#

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?

kindred cosmos
#

@hexed linden please link me source

hexed linden
kindred cosmos
#

@hexed linden line 237

hexed linden
#

its commented

#

i'm using UserMixin

#

actually... yes, it makes sense what you're saying

kindred cosmos
#

You did inherited it wrong

hexed linden
#

what would the solution be

kindred cosmos
#

Should class accounts(UserMixin, db.Model): not class accounts(db.Model, UserMixin):

#

Should be*

#

Mixins go first

#

Try that

hexed linden
#
  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 -```
kindred cosmos
#

Oh you to make sure your ID variable is id not ID

hexed linden
#

ah thanks

#

let me try now

kindred cosmos
#

For the record all variables should be lower case

#

Check out pep8

hexed linden
#

my database has them as uppercase, don't know why :/

#

anyway, thank you so much, legend 🙏

kindred cosmos
#

Haha np

#

Did it work?

hexed linden
#

yeah

#

it works great

#

thank you so much

kindred cosmos
#

No problem mang

#

Just update your stackoverflow post so that isn't lingering without an answer

#

@hexed linden

hexed linden
#

ah

#

yes

#

will do, thanks

kindred cosmos
#

Cool

terse shore
#

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.
terse shore
#

My brain is officially broken 😦

last forge
#

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).

deep cave
#

@native tide you might wanna show us your jinja.

magic scarab
#

hello i have a problem with my website when i press right arrow my website moves to the right how do i fix that ?

deep cave
#

@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

forest parcel
#

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?

rough magnet
#

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

kindred cosmos
#

@rough magnet Are you using nginx or apache?

rough magnet
#

neither

#

i haven't uploaded it

#

@kindred cosmos

kindred cosmos
#

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

rough magnet
#

@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

kindred cosmos
#

Use "```" at start and end for your code

#

It makes it easier to look at

#

Which function is your recursive function?

rough magnet
#

i don't know where to start that's the problem @kindred cosmos

#

i havent used these type of algorithms before

kindred cosmos
#

You're better off reading up on recursive functions then trying to use one if you never have you used them before

rough magnet
#

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

kindred cosmos
#

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

native tide
kindred cosmos
#

Both flask and django could do both

#

It just depends what tool you want to do it

native tide
#

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

forest parcel
#

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?

final kayak
#

you don't

wheat trellis
#

Wow flask is fun

#

I like it

calm garnet
#

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

opal leaf
#

itll be easier on the end user if you use a reverse proxy instead

#

also means you wont need multiple/wildcard ssl certs

calm garnet
#

Honestly not sure about using reverse proxy?

opal leaf
#

lets you map specific paths on a server to a whole other server

calm garnet
#

Ahh, ok

opal leaf
#

eg /static requests could all be forwarded to another server

calm garnet
#

Aka flask

opal leaf
#

ye

calm garnet
#

In my scenario

#

Would I configure that through my domain carrier?

opal leaf
#

on apache

calm garnet
#

Ohh ok

opal leaf
#

on the main domain

calm garnet
#

Thank you

calm garnet
#

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

native tide
#

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?

night glen
#

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

calm garnet
#

Flask-sqlalchemy

#

I like it.

glacial quartz
#

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

hexed linden
#

@wheat trellis ikr man

#

@native tide you don’t

#

as they said.

#

you should use something that automatically generates a salt, like bcrypt

wheat trellis
#

Sorry I have no idea what I said

hexed linden
#

flask being fun

wheat trellis
#

Oh right

hexed linden
#

I think it’s great

wheat trellis
#

Yeah I love python and microservices

#

So seems perfect for me

hexed linden
#

😁

#

Have you heard of bottle before

wheat trellis
#

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

hexed linden
#

Bottle is a micro framework like Flask

#

However it doesn’t have the cool extensions that flask does

#

they look so similar tbh

wheat trellis
#

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

hexed linden
#

Gl 😁

native tide
#

Should I use Socket.IO? Or is there another module that is better to use?

surreal kayak
#

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)

glacial quartz
#

KeyError: '_apispec_request_data_name'

#

hmm but if somone dosent send data: { "somestuff":"2323232az" } i get a crash 500 interanl error

gleaming ice
green badger
#

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.

glacial quartz
#

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?

opal leaf
#

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

torpid terrace
#

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!

torpid terrace
#

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.

wary talon
native tide
#

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

slender comet
#

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

torpid terrace
#

@wary talon thanks I'll take a look!

tender sphinx
#

are all status codes under 201 fine?

#

or should i only continue when the status code is 200

surreal kayak
#
#

but unless you've created an item in an API or it just a web page, 200 is the better response code

tender sphinx
#

okay so if response.status == 200 is preferred over if response.status <= 201 if im making an api call

little nexus
#

all 2xx codes mean success

#

1xx is informational
2xx is sucess
3xx is redirection
4xx is client error
5xx is server error

granite wigeon
#

anyone around to help with a gunicorn service file, i keep getting an error about it failing to load

granite wigeon
#

finally figured it out

torpid terrace
#

@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.

quiet kite
#

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 ?

native tide
#

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

wary talon
#

@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

vagrant adder
#

@quiet kite youtube has a lot of good resources

quick spruce
#

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?

hollow flower
#

Has anyone here used Enom API?

opal leaf
#

@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

quick spruce
#

i need to pass 2 variables from javascript to a flask form, any ideas?

opal leaf
#

you can make a hidden field that you use to store that data, just set it before its actually submitted

#

<input type="hidden">

quick spruce
#

@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

opal leaf
#

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

limber hemlock
#

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.

still briar
#

user = IntegerField(default=123) ?

#

Haven't used Flask forms, but this might do the trick.

limber hemlock
#

I want to send data from the form that is in html.

#

maybe something like "form.user = user"

still briar
#

You want to call a server side function without the submit?

limber hemlock
#

form.submit() is already there.

shrewd sand
#

Can you not define the action part to trigger something?

#

Or is that just a php thing?

limber hemlock
#

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

shrewd sand
#

I think you can get action to trigger that route

#

2 secs

limber hemlock
#

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.

shrewd sand
#

@limber hemlock

limber hemlock
#

thks, I'll check it out

shrewd sand
#

;D

quick spruce
#

@limber hemlock any luck, I need to do the same thing

limber hemlock
#

Yes, I figured it out.

shrewd sand
#

Glad you got it

limber hemlock
#

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>
quick spruce
#

low i could kiss you if this works

limber hemlock
#

the main thing I was missing is "value="

#

kek, it took me hours to figure it out

quick spruce
#

6 hours of stress man

#

lol

#

i feels

limber hemlock
#

hope it helps, its working for me ;D

quick spruce
#

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

limber hemlock
quick spruce
#

sadly thats only for dropdowns :/

heady basin
#

anyone know if having a slug in the url has any affect on seo compared to having the arg as a get param

elder nebula
#

Why does that number after get, is so big?

#

It keeps getting bigger and bigger

quiet solstice
#

What is the size of MaglaVerde.png?

elder nebula
#

26,8 mb

#

Oh its bytes

#

Nvm

#

Thanks for saying that size thing.

#

So png is not good if you have lots of images

hexed linden
#

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 😄

hexed linden
#

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.

thorn vapor
#

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

opal leaf
#

"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

deep narwhal
#

Does anyone knows a tutorial to connect gmail using ssl and communicate using pop3 protocol that you created?

thick light
#

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?

unborn terrace
#

@thick light what do you mean?

#

@deep narwhal there are plenty, just google it, you'll find them in seconds

thick light
#

@unborn terrace could i boher you in private for a minute?

#

bother* even

unborn terrace
#

@thick light nah just tell your issues here

#

if I can't answer someone else might be able to

thick light
#

didn't want to spam

unborn terrace
#

that is not spam, it is the whole point of this discord

thick light
#

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
#

well, just make requests to your API

#

like you would for any

deep narwhal
#

@unborn terrace they use the pop library

unborn terrace
deep narwhal
#

I can't use that

#

@unborn terrace that's my problem

unborn terrace
#

Why?

native tide
#

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?

limber hemlock
#

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())
unborn terrace
#

@native tide load them into your configuration system or something like that

deep narwhal
#

@unborn terrace university work

unborn terrace
#

Checkout the Wikipedia article for some overview

deep narwhal
#

Yeah i need to use that

unborn terrace
#

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)

deep narwhal
#

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

unborn terrace
#

C has libs for pretty much everything, as most languages

native tide
#

@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.

glacial quartz
#

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 ?

timid arrow
#

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

glacial quartz
#

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?

lost saddle
#

@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

lost saddle
#

What is the url generated for your statics? @native tide

lost saddle
#

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

meager anchor
#

why would / be showing the index.html page?

lavish sand
#
<article class="message is-dark" style="width:500px; display: inline;">
#

you'd ideally want to use a non-fixed width though

#

@bronze ermine

#

rokanaisu np

meager anchor
#

some webservers do that by default and it's more or less convention but usually that won't be done automatically

limber hemlock
#

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?

rustic field
#

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?

limber orchid
#

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?

upbeat egret
#

how do you do footers in flask? i've spent an embarrisingly long time trying to figure it out

fathom prism
#

@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?

native tide
#

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

upbeat egret
#

@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?