#web-development

2 messages ยท Page 46 of 1

little steppe
#

yeah pretty much

native tide
#

Do it.

rustic pebble
#

I would have a script on python do that

little steppe
#

that's what I do, I was wondering if I could update a routing rule

#

ya

rustic pebble
#

scan through the line of all your html files

native tide
#

Its most likely a feature of whatever editor you use already

rustic pebble
#

and replace the urls with that

little steppe
#

yeah that's how I've been doing it

#

thanks for the help friends ๐Ÿ˜„

rustic pebble
#

np

native tide
#

There is a part of me that wants to take the time to pick up sass. But I also feel like its so unnecessary, especially as I dont exaclty want to focus on front end. I would rather tweak someone elses CSS that start from the bottom, at which point sass seems really useful.

#

unnecessary for me*

#

obviously people out there writing css from the bottom should learn it

native tide
#

This is in my forms action
/post?id={{g.id}} but for some reason it isnt adding the id argument

#

Is that in a template?

#

yea

#

its not adding the ?id at all

#

Try to print g.id in the html to see if its being passed the variables. It probably is if its missing ?id=

#

But just to be sure

#

It might remove ?id= if its getting nothing as a value tho

#

if you're using django you can probably use {% url 'template_name' g.id %}

#

I think

#

But you have to assign a name to that route in the urlconf

#

im using flask

#

ah ok nvm

#

Its still not adding the arg

#

Did you try displaying it in the html somewhere to verify that the template is getting the object?

#

Or is it displaying any other variables?

#

In flask, do you pass a template its variables from the route/view?

rustic pebble
#

@native tide seems like .id is an attribute to g why not try rendering the jinja template with .id pre-given

tired root
#

Show me where you set the g value, @native tide

#

If you do it with current_app.context(): that creates a new context

native tide
#

You guys make me want to look at Flask everyday

#

haha

#

I changed it to just have {{id}} and it's printing the right if

#

Id

#

Sorry for the long response

#

Even if it was printing none it'd still do ?id=None

#

do i need to add something ? related on the endpoint?

#

hmm

#

seems the url wont change at all in the form

#

what is the full code for the entire element?

#

a button element?

#

I have this going on in mine <a href="?page={{ page_obj.paginator.num_pages }}">Last</a>

#

So it should work.

native tide
#

Nevermind mine was messed up

#

i couldn't figure out how to do the ? thing though in my app.py

opal radish
#

Is it possible to keep changes made to the current_user with flask-login

#

I am trying to change a property but the changes are not saved when it is accessed from a different route

hollow flower
#

How does one use the Django 3.0's models.IntegerChoices when declaring a model?

rustic pebble
#

Flask-login is not very reliable currently

#

I use authlib

opal radish
#

Argh

#

So you don't know if it is possible?

#

I'm desperate at this point. Just rewrote a an entire thing to use flask login]

#

I guess the real question I am asking is is it possible to store a Python class, similiar to how you can store normal values in the session variable using Flask

rustic pebble
#

I am not entirely sure

#

I use cookies for that manner

opal radish
#

Cause I have a class with way too many variables and stuff to manually convert into JSON

#

And cookies == session right?

rustic pebble
#

Kinda

opal radish
#

well is there a way to store a class in cookies

rustic pebble
#

If you use cookies make sure to sign them using a JWT

#

There is a way to store user data in a cookie

#

Then after getting it you can recreate the user class

opal radish
#

what is this way

rustic pebble
#

Look up how JWT and flask cookies work

opal radish
#

kk thanks

rustic pebble
#

You will find it quite easy

opal radish
#

@rustic pebble do you think i could use jsonpickle

tired root
#

@opal radish Anything on side of the user is to be considered unsafe and compromised

#

so storing classes there is kind of a stupid idea, to be blunt

#

and storing the state of classes is a bad idea in webdev in general

#

store the data, but in a database as atomic values with relations

opal radish
#

Wdym byt atomic?

#

by*

tired root
#

one value per database column

opal radish
#

ah

#

Well I guess I'll do that then. Thanks for the advice.

tired root
#

So you don't store "Martin Miller" in one field

#

it's two fields

opal radish
#

first and last?

vagrant adder
#

For my last project i used jwt for auth

tired root
#

yes @opal radish

vagrant adder
#

Worked wonderfully

opal radish
#

I use discord oAuth for this project,

tired root
#

don't store the credentials in a cookie

#

save the bearer token and the refresh token in a database

opal radish
#

@tired root is it ok if I dm you if i run into problems?

#

if not thats perfectly ok

tired root
#

ask here please

#

I am doing stuff here, I can't always answer

opal radish
#

ye no worries.

rustic pebble
#

@tired root storing data such as usernames in a signed with private key jwt cookie

#

Isnt exactly unsafe lol

#

Ofc you are not going to add pws on that

tired root
#

but storing pickle is

rustic pebble
#

I dont use pickle

tired root
#

and usernames aren't sensitive no

#

but tokens are

rustic pebble
#

What is pickle

#

Ive never used it

tired root
#

then why do you disagree?

#

why do you tell me I am wrong when you have never used it?

rustic pebble
#

I mean I have a knowledge of what it is

#

But I know people dont suggest it

#

So I guess that it isnt good

#

That is what I mostly use

tired root
#

Serializing means putting an object as it is into a format that can be read back. Many games do this and save their entire state to the disk, so they can reload it later

#

also known as quicksave

#

if one were to edit that data, you could theoretically execute arbitrary code

#

in a remote context, using that is undesired, to put it mildly

rustic pebble
#

Yeah but even then I also store the token value in a something I call server side cookie and each time a user requests something that needs more than guest permissions the two tokens get compared

#

If the client one is changed it logs the user out

tired root
#

storing something and using pickle are 2 totally different things

rustic pebble
#

I am talking about jwt

tired root
#

jwt plays no role here

rustic pebble
#

Sure

tired root
#

Hmm this is kind of an abuse of css ๐Ÿ˜›

#

but it works

rustic pebble
#

??

gleaming herald
#

I have a chatbot that works on WebSockets. For the client who is on a website can easily connect. (As session would stay connected in browser)
But for the client who is conversing through APIs (in case of WhatsApp) there needs to be a middleware that will do this.
So for each client, there should be active WebSocket connection. If the same client is sending the message, the old connection should be used and respond.

#

How do I do this

jagged lark
#

You want to recover a WebSocket connection?

gleaming herald
#

Yes, kinda

#

If a same user sends a request again I wanna use the same connection

#

consider there is a unique id for each user in the API request @jagged lark

jagged lark
#

You can't really recover a WebSocket connection, at least not easily, you'll be better creating a new one using the same ID

gleaming herald
#

I don't think that will help

#

Creating a new websocket connection would reset the context

#
hi_flag = False
message = await websocket.receive_bytes()
if message == "Hey":
    hi_flag = True
    reply = f'hey, there {user_id}'
    await websocket.send_bytes(reply)
    message = await websocket.receive_bytes()
    if message == "hey":
        reply = f'Hey you already said Hi ! WTH !'
        await websocket.send_bytes(reply)

if message == "Goodbye":
    if not hi_flag:
        reply = 'Hey You did not say HI !'
        await websocket.send_bytes(reply)
#

Consider this example @jagged lark

#

This is a pseudo code

#

what if I want a middle ware
It will get a API request with a unique USER_ID

#

After sending the message that API will return the response

#

If I get the same USER_ID again it should use the same connection since if you see the pseudo code above, you'll get it

jagged lark
#

By definition, you can't recover a WebSocket connection, you need to reopen it

#

Yes you can have the client send you the same ID

gleaming herald
#

reopen it?

#

so it would be a new connection?

jagged lark
#

Yes

gleaming herald
#

Hence it would not wokr

jagged lark
#

If the connection drops for whatever reason, the connection is dead and you need to open a new one

gleaming herald
#

There should be a way out for this?

jagged lark
#

I mean, the client could simply store the ID and use it to reopen the connection

gleaming herald
#

How do we do tha

#

that

#

open a connection where ID is known

#

because when I connect there is no option to mention the websocket number / id number it should connect

jagged lark
#

You can supply parameters through the url, the same way as you do with http

gleaming herald
#

I think you are misunderstanding the problem

gritty carbon
#

hey guys can i ask question now or there is some case open?

#

cause it's hard to tell for me ๐Ÿ˜‰

rigid laurel
#

You're probably ok to ask

gritty carbon
#

Ok thanks

#

so i have problem with circular import in my models i was searching for solutions and i found 2 :

  • to use path to model instead of importing it
    It does not work for some reason when i do
games_subbed = models.ManyToManyField(posts.Game, related_name='subbed_game')

i'm getting error :
NameError: name 'posts' is not defined
Yes apps are in proper order

  • Second solution is to use apps.get_model()
    but that doesn't fix my circular import problem
#

i can throw my files to some paste.bin if needed

#

but TLDR :

#

localusers/models.py ->

#
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.apps import apps
games_subbed = apps.get_model(app_label='posts', model_name='Game', require_ready=False)
...
class LocalUser(AbstractUser):
    verified = models.BooleanField(default=False)
    servers = models.ManyToManyField(DiscoServer, through='Membership', related_name='servers')
    games_subbed = models.ManyToManyField(games_subbed, related_name='subbed_game')
...
#

posts/models.py ->

#
from django.db import models
from localusers.models import LocalUser


# Create your models here.

class Game(models.Model):
    title = models.CharField(max_length=200)
    image = models.ImageField(upload_to="images/")

    def __str__(self):
        return self.title


class Event(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()
    start_time = models.DateTimeField()
    end_time = models.DateTimeField(null=True, blank=True)
    game = models.ForeignKey(Game, on_delete=models.CASCADE)
    creator = models.ForeignKey(LocalUser, null=True, on_delete=models.CASCADE, related_name='creator')
    players = models.ManyToManyField(LocalUser, null=True, related_name='player', through='Participation')
...
#

problem is that Event need LocalUser

#

and LocalUser need Game

#

is calling models by appname.modelname not working anymore?

#

ahh forgot about traceback but it's quite enigmatic

lavish prismBOT
#

Hey @gritty carbon!

It looks like you tried to attach file type(s) that we do not allow (.txt). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .m4v, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg, .md.

Feel free to ask in #community-meta if you think this is a mistake.

gritty carbon
#

ImportError: cannot import name 'LocalUser' from 'localusers.models' (/home/duskhorizon/Desktop/discoplaytogether/localusers/models.py)

#

is at the end no matter if i do circural import by purpose

#

or i use getmodel()

#

that is confusing me

#

but when i remove any mentions of 'Game' it works as charm

#

i had spend some time fixing that any contribution would be appreciated

modest dirge
#

i deployed my first website yesterday

#

on github

vagrant adder
#

Great!

latent pebble
#

Heya guys, I'm wondering what the differences are (in general) between a shared hosting, a virtual private server, and dedicated hosting when it comes to direct control with SSH.

  1. If my shared hosting provides an option to control my "share" of the machine, what limitations should I expect? I'm guessing since they're running on the same machine without a virtual server -- I would not have root access and would be limited to my own folder, right? Is there any way for them to give me root access anyway? Any other limits?
  2. As for VPS vs Dedicated hosting, are there usually any differences between the two when it comes to control via SSH?
native tide
#

My hosting experience is limited, but I once I had shared hosting with HostGator where they gave me ssh to my own folder, but I literally had to call them an sit on the phone for an hour everyday to get it working. Then by the end of the day, they would be blocking my connections again, and I'd have to call the next day. Do not recommend them by the way. That was when I was less informed.

#

That isnt even the worst thing about them. The worst thing is that they try to sell you the least secure setup they have for an outrageous price and then act like security is an extra feature that not everyhone needs.

#

Like they want you to pay for SSL. lol

haughty saffron
#

how can i do some sort of asyncio.sleep() but in javascript?

rigid laurel
#

what are you actually trying to do?

#

you can do ```js
setTimeout(() => {alert('delayed')}, 5000);

#

I don't think that should block any other code @haughty saffron

rigid laurel
#

@native tide I think learning React (or possibly Vue or Ember or another web app framework) is probably the most useful next step from Django. It lets you take a step from building websites to building web applications. Also by learning React, you learn just general JS pretty well in the process.

I don't think there's a huge amount of value in learning Flask if you don't find yourself disliking Django, a lot of the core ideas are very similar.

Learning React exposes you to a new way of doing things, but at the same time doesn't throw away what you've learned so far.

I'll also ad the caveats to this that I've written more JS than I have Python, and I've not got a huge amount of experience with react, Django or Flask - but I am comfortable with all 3

native tide
#

I'm more or less on your train of thought though. Even if I eventually dont want to rely heavily on JavaScript anywhere that I don't need to, the entire web is using it a lot, and I need to be familiar with it. In fact I know that several things I want to do can only be done with it. If it will help me improve my vanilla JS in the process, that's great. I'm mainly hoping that whatever JS I want to add will integrate with the SS rendering I would rather do where ever I can.

#

But yeah, you've sold me that its a good next step.

#

Are React docs as good as Django docs?

#

I find that with frameworks that are rapidly developing new features its best to learn it directly from the makers

rigid laurel
#

React docs are pretty good for the very early stages of learning. But once you have the basics down, it gets a bit iffier

native tide
#

Yeah, well, that's Django too. You just have to get good at reading code at that point.

rigid laurel
#

I learned React by just being thrown into the deep end by having to work on an app that was in production - so my learning experience was pretty atypical

native tide
#

yikes

undone copper
#

hey guys , I need to log database queries to log file and i'm usng django db.backend to logger

#

the problem is it logs all queries at DEBUG level when i make error with raw sql

#

shold i ovveride the CursorDebugWrapper to log as ERROR level log if so?

latent pebble
#

Thanks for the tip TLS, that doesn't sound pleasant, I'll avoid HostGator's shared hosting then

native tide
#

To be fair, I think they didnt like my VPN. But shrug.

#

Still better options

#

So, this doesn't work if I turn off the Babel preprocessor. Is that typically what you need to use React? I would prefer to work somewhere that is not this little website's fiddle.

How would you go about setting up this environment.

In fact, that's one of my least favorite things about JavaScript is I want to work in real editor that otherwise perfectly emulates the browser environment

dense slate
#

Has anyone used a payment gateway to both 1) charge service fees on each transaction and 2) also accept paypal? What gateway did you use?

ionic rain
#

Maybe, the payment gateways has a specific apis. I think you need create different url for each payment. In Brazil we have a PagSeguro and others easy ways

dense slate
#

Hmm, so I'm wondering how websites are able to charge service fees as well as take Paypal. As far as I can tell, no gateways, including Braintree, allow for both. So how would a site take paypal and also impose a transaction fee?

tired root
#

Why impose that fee at all?

native tide
#

Because webdev lol.

#

The web used to be a more decent place. There were less people on it. Sure it was still heavily made up of porn and other shady things, but the entire web wasn't a giant screw in the face. I know that there is no use living in the past, but some things about the old web were better

#

That's why when people come to me and say, "This is how we're developing today," I dont necessarily want to be exactly like them.

#

That being said, I have started my React lessons.

#

I'm having fun with it.

native tide
#

These are all the node modules installed by npm's create-react-app

#

Is this really what you have to deploy with every react app?

#

That is not sane.

tired root
#

@native tide Now you know why I avoid npm and react

native tide
#

jesus christ

tired root
#

Not only the sheer amount, but those tools have a history of malicious packages

native tide
#

Yeah all my friends of hackers.town hate it too

tired root
#

and people importing 2 line addons because they are too stupid for an if

native tide
#

I am blown away

#

I'm still gonna play with it because I dont want to be ignorant

#

But wtf

#

lol

#

Is there a more light weight manner of setting up a react environment than this huge massive amount of things?

#

Because this was automated for me.

#

If I could do this manually in a more sane manner, I would prefer that

tired root
#

probably not

#

those are probably all dependencies

native tide
#

Honestly, I'm pretty sure that I'm going to come away from this only more strongly feeling how I already feel. But I know that everyone uses this so Im gonna learn it. But... I imagine myself just using vanilla JS and server side rendering to be honest.

#

I dont even think jquery is this big

#

Maybe its more broken but

#

I used to think that the reason they pack out JS in the minified form was to obfuscate the code.

#

Which Im not entirely convinced isnt part of the reason

#

But i see that the main reason

#

Is that this is too fucking big

tired root
#

It cuts down the size

#

obfuscation is a side effect

#

You should btw always look for ways to minify your code, html or js or css

native tide
#

I realize that now. I used to think it was intentionally trying to obfuscate, but it makes sense now that I see how massive these things are.

tired root
#

When I turn off flask-minimize, my web page has 89 lines

#

60% is white space

#

from the template generator

native tide
#

Right.

#

Lets say that I only import half of these modules in any file in the app

#

Is there going to evertually be a way to pack it out only with what Im using?

tired root
#

I don't know tbh

#

never really used react or npm

#

as in, doing more than taking a gander

#

I have it mainly for tools on my pc

native tide
#

I kind of want to make certain interactive experiences in a web game. But what I definitely don't understand is why you would use this to make a common document page.

#

Its like using a flamethrower to kill a roach

#

Either way im gonna learn this stuff so if for no other reason

#

Im not the person hating something I dont know anything about.

#

What I'm really hoping for is that 90% of my site can be a document based, template rendered from server python app...

#

But that on certain pages

#

I can initiate little JS experiences, save the results of them to database, and move on.

#

I dont need to constantly be XHRing the server to load new shit on the same page

tired root
#

On my skill queue, I have a progress bar

#

it shows how far a skill has progressed in training

#

The API request has start and end date, if it is training

#

I am using the template generation to set that bar to the progress relative to start and end

#

it persists between refresh and the browser animates it on it's own

#

Javascript: 0

#
        @keyframes progress-bar {
            from{ width: {{ training_percent }}%; }
            to{ width: 100%; }
        }
        .progress-bar-container .progress-bar{
            position: absolute;
            background-color: #66fcf1;
            top: 0;
            width: 20%;
            height: 1.75vh;
            z-index: 1;
            animation-duration: {{ training_seconds }}s;
            animation-name: progress-bar;
        }```
native tide
#

Interesting. You can do a lot with CSS.

#

Ive never used keyframes in CSS before. I should look into that

#

I didnt realize you could template render css.

#

thats a great idea

tired root
#

No, I render that into the head

native tide
#

ahhh

tired root
#

with a <script> tag

#

the browser interpolates the values between the percentage points between the keyframes

#

so you can give it from 0-100 or more points to interpolate between

native tide
#

I might snippet save that.

tired root
#

the template generation code is quite big though for that

#

but then,it needs a lot of logic

#

it's my heaviest page so far

#

190 lines of python

native tide
#

So keyframes is for defining the name of an animation?

tired root
#

well, for the whole calendar

#

yes

#

you can apply that animation to any element

#

that supports the animated values

native tide
#

what triggers the animation? On load or appearance of the element?

tired root
#

if the element is visible on load, the load

native tide
#

ok

tired root
#

the animation happens as soon as the element is in the DOM

native tide
#

got it

tired root
#

so many drag and drop libraries

#

ever used one, @native tide ?

native tide
#

nah. for JS you mean?

tired root
#

yeah

native tide
#

I haven't really used a lot of JS in general. I've gone over the basics. But Ive never used it to build anything, mostly because it annoys me.

#

But I think part of the problem was I was approaching it wrong

#

and by gone over basics I mean, I am familiar with the syntax enough to read it.

#

But I have never built anything using it

#

Other than like

#

Grab this div, make it appear when I do this.

#

Kind of thing

tired root
#

This is going to be very difficult to make

#

Because every skill has a depedency

#

not sure how to implement that in js

#

probably need to xhr the flask app and have python resolve it

native tide
#

I imagine that will be my goto constantly.

#

Damn, I have to get to bed. Its late af over here.

#

I'll see ya

tired root
#

o7

toxic marten
#

Today i've just updated vs code, and i have a strange "problem" with directory

#

Why static and style, that are 2 different folder, are on the same line? How can i set the preferences that folder are not inline?
It doesnt obv create errors, but it confuse me. I'm used to seeing them on different lines

native tide
#

Anyone using pycharm ?

#

Should i go for pro ? Been using community version for some time and i really like it

tired root
#

if you want the template support sure

#

there is a 30 day trial btw

vagrant adder
#

i have never liked ide's in general

tired root
#

@native tide

native tide
#

Yeah im kinda interested for that flask support tho

tired root
#

Flask support is great

#

supports jinja and recognizes missing tags also in child templates

#

it evaluates all files included

native tide
#

Great u guya gonna be envy when i create "new facebook" ;)

#

Especially @vagrant adder

tired root
#

joke's on you. I've already done it

native tide
#

Hahah

#

Xd

vagrant adder
#

yeah jokes you on i have made twitter clone

#

:dab::

native tide
#

We rich

vagrant adder
#

@native tide vscode has flask and django debugger support too

tired root
#

but it is really not as extensive

#

working with pycharm is a whole different level compared to vs code

vagrant adder
#

unfortunately

native tide
#

I just cant get myself working in vs...

#

I was using atom prior the py

tired root
reef zealot
#

Hey, any python web developer willing to hop in a voice chat later to help me with some questions regarding web development with python?

bleak bobcat
#

How about you ask them here and if you don't get the answers you're looking for then we can vc ? That way more people would benefit from it

#

If you're a student @native tide you can get the whole jetbrains suite for free

reef zealot
#

You are right, basically I'm looking to get into web development with python, I know some Django (created a simple portfolio website that I'm currently still working on) and I'm looking to do some free websites for friends/small businesses to add to my portfolio.

#

I'm looking for advice on how should I go about this. Should I go with Django or some lighter framework? (I want to start with some basic landing pages, blog type websites)

gloomy blade
#

have you worked with flask before?

reef zealot
#

Currently I'm learning js and I plan to polish my css and html skills doing these projects

#

Ive heard about it but never used it

gloomy blade
#

if you're planning to go with basic stuff i would say you should go with flask

#

django is good for more scalable apps

#

but if its basic flask is nice

reef zealot
#

Does it have an admin page like Django? Let's say the user wants to edit some stuff on his own then he can do it himself

gloomy blade
#

nope

#

reason because its meant to build basic apps

#

although you can easily build an admin page if you want

#

also its like very diluted version of django so if you've worked on django before flask will be easy to start with

reef zealot
#

I heard it's easier to pick up than django

gloomy blade
#

it is indeed

dense slate
#

It is lighter and easier to pickup, but I'll throw a vote in for Django because it does have many of the things you might want to later add to a flask app. Yes, you might be including it if you don't need it, but I end up using a lot of that stuff as the app grows.

reef zealot
#

I have to add that my knowledge to databases its limited, I've only worked with them trough Djangos orm using sq3lite

dense slate
#

And having a default admin installed for the ORM is really awesome.

gloomy blade
#

well there are things to lookout that you might add in your app

#

based on that you can decide which framework to go with

dense slate
#

Also what do you mean by "go about this"? Go about learning Django/Flask/etc.?

reef zealot
#

For know I think I'm going to stick to Django since I know it. Also I'm learning Javascript atm, I don't really want to overwhelm my self with all this

dense slate
#

I found that just creating what I wanted to create, while implementing different tools as you go, is really the best way I learned. If I couldn't figure out how to implement what I wanted, I just researched it and kept trying until it worked. That, of course, is figuring that you have at least a solid python understanding.

#

And by solid I really just mean basic operations.

reef zealot
#

One more quick thing, is there a Django plugin for blog type websites. I have a blog section on my personal website and the content part is just a text field. I would like to be able to modify the text, add images links etc. Any idea how would I go about doing that?

dense slate
#

There are most likely Django libraries that are built to do this. You could literally google for django blog, and probably find what you want.

reef zealot
#

I feel like I know the basic python stuff. I've also built a couple apps using pyqt5 with some webscraper scripts attached to it, nothing huge tough

dense slate
#

There is a really good tutorial, written Django Girls I think, that introduces you to Django by creating a blog.

#

It was super helpful for me early on.

reef zealot
#

I have my website up and running just have to mess with the css abit to make it work properly on mobile

#

Gonna check out the tutorial, thank you

bleak bobcat
#

@reef zealot I would like to be able to modify the text, add images links etc. Any idea how would I go about doing that? Look into tinymce / ckeditor / summernote they all have django specific libraries

reef zealot
#

Thank you BassSpleen

native tide
#

@bleak bobcat Yeah my student days are long gone bro , thnaks either way

native tide
#

Is the yarn ecosystem any better than npm?

#

Imagine if in order to make a python app you had to do python3 -m pip install * and there was that historical list of problems with pypi.

rigid laurel
#

Yarn isn't really better than npm - and you can still get npm packages with it

native tide
#

mm

restive kindle
#

I have a problem regarding 'background-image' which's URL is a page that gets an SVG and fills it with a certain colour - and it doesnt load. The script is in PHP and upon going to the page in the browser the SVG renders perfectly. I was wondering does 'background-image' have some sort of timeout or is my SVG malformed?

CSS:

background-image: url('/api/core/get/image/svg.php?path=/images/icons/material/image/svg/production/ic_image_48px.svg&fill=fff');

SVG (filled):

<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48" style="fill: #000; ">
    <path d="M42 38V10c0-2.21-1.79-4-4-4H10c-2.21 0-4 1.79-4 4v28c0 2.21 1.79 4 4 4h28c2.21 0 4-1.79 4-4zM17 27l5 6.01L29 24l9 12H10l7-9z"></path>
    <style>svg * { fill: inherit !important; }</style>
</svg>

I am confident there is nothing wrong with the PHP script.

**Edit: I did figure out what was wrong. The Content-Type was 'text/html' not 'image/svg+xml' thereby the browser wouldn't accept it.

native tide
#

Do you intentionally have an absolute path from root or should that be a relative path?

restive kindle
#

I check its a safe path dw and yes, its intentionally absolute

native tide
#

Are you confident its not a permissions problem? If not that I got nothing.

rustic pebble
#

So I am returning this from a request to my server

#

This is a nested dict of course, I am trying to access the values of Data but I cant

#
function showdata(){
    data = get_data();
    console.log(data);
    for (i in data['Data']){
        console.log(i);
    }
}
#

This only logs the data but not the i

native tide
#

I'm a little torn between thinking that npm is awful and that React is a little fun. It's like knowing that going to the strip club and blowing all your money on cocaine and hookers (I don't do this btw) is probably going to get you a disease, but its probably fun to do. ๐Ÿ˜›

#

Either way, I have meetings all day, so no time to play with it

rigid laurel
#

NPM is definitely awful (but I find it much easier to use than anything in the Python ecosystem)

fringe fog
#

a JS question ...
I have an old system trying to get a user's timezone with geolocation which is a bit problematic for a variety of reasons.
I see now, Intl.DateTimeFormat().resolvedOptions() (and the timeZone attribute) are working pretty well across the board, so I may be able to use that now.

Anyone else getting a user's timezone?Have any problems with Intl recently? or someother reason to still use geolocation?

tired root
#

I don't see why you'd use a service just to get the time zone

fringe fog
#

yeah I don't see a reason either, but I thought I'd ask to see if anyone has ran into a reason. This app was written about 10 years ago, so there is a lot I am running into that doesn't seem to make much sense anymore.

#

Thanks for the link, btw, I saw that too, curious if I'd see any difference between the data I get from Date and Intl, presumably not.

tired root
#

Well, Javascript embedded in HTML always runs in the browser

#

so any date constructed has a local timestamp

#

The only thing you cannot solve this way, is if the user's pc has a different TZ

#

but then, I am a big proponent of respecting the users settings

#

That was probably the rationale behind using a geoip service

#

to get the real timezone

#

BUt I say it is a real edge case where people have a different TZ set than they are in

fringe fog
#

yeah, with the service they chose we were seeing all sorts of issues like their location being across a tz border, vpn issues, and other innaccuracies. I think respecting the user settings is best, there is no reason to try to not trust the user they could always manipulate the results if they really wanted to. It's better for it to be simply explainable "the site shows this because of a setting on your computer, which you can change." I think the oringial intent was to not trust the user but that seems awefully misguided to me.

rustic pebble
#

but I am using this

#
<script type="text/javascript" src="{{ url_for('static', filename='js/charts.js)') }}"></script>
tired root
#

Because there is a ) before the '

#

charts.js)

rustic pebble
#

oh

#

thanks

#

๐Ÿ˜›

dusky osprey
#

in flask if decorate a handler with @app.errorhandler(SomeException) why is it still throwing the exception? how do I catch it?

#
    def handle_expired_error(ex):
        response = jsonify({
            'message': 'Token has expired'
        })
        response.status_code = 401
        logger.info(f'{ex}')
        return response```
undone copper
#

hi guys i want to ask how to extend(modify) django database backend

shadow rock
#

@dusky osprey why dont you just do a normal try except block

dusky osprey
#

@shadow rock where should I put it? that exception is thrown each time a jwt token is expired

shadow rock
#

which jwt library are you using

dusky osprey
#

flask_jwt_extended

shadow rock
#
from flask_jwt_extended import JWTManager

jwt = JWTManager(app)

@jwt.expired_token_loader
def expred_token_callback():
    return {"msg": "EXPIRED_TOKEN"}, 401
#

this assumes you're just flask-restful so you dont have to jsonify

#

but if you are not using that library, just go ahead ahead jsonify

rigid laurel
#

You don't need to jsonify in normal flask either

shadow rock
#

oh really? i thought you had to

rigid laurel
#

I think in one of the relatively recent updates they made it so you don't need to

shadow rock
#

cool

rustic pebble
#

@shadow rock btw if you are implementing this for sensitive data, dont use flask's JWT, try out authlib

shadow rock
#

@rustic pebble authlib seems like a library to help implementing oauth

#

and depending on how your auth is set up, you may still end up using jwts

rustic pebble
#

search for authlib jose

shadow rock
#

that's what im saying, you use oauth to connect to a provider and make sure the user is authorized, and then your server still sends back a jwt in which authlib will handle

#

devs shouldn't use this library if they're just strictly doing jwt and auth themselves

#

its a lot of library for a simple process

ember rose
#

hey im new in this server, does anyone know why i am getting this message with flask even though i have set a secret key?

#

sorry if im interrupting something but i have an urgent project and im a bit of a noob with this

#

andim trying to get all the help possible

shadow rock
#

show you flask configurations

ember rose
#

havent used python in years sry lmao

shadow rock
#

it should look like this

#
app = Flask(__name__)
load_dotenv(".env")
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URL")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["PROPAGATE_EXCEPTIONS"] = True
app.config["JWT_BLACKLIST_ENABLED"] = True
app.config["JWT_BLACKLIST_TOKEN_CHECKS"] = [
    "access",
    "refresh",
]
app.config["CELERY_BROKER_URL"] = "redis://localhost:6379/0"
app.config["CELERY_RESULT_BACKEND"] = "redis://localhost:6379/0"
app.secret_key = os.environ.get("APP_SECRET_KEY")

api = Api(app)
jwt = JWTManager(app)
cors = CORS(app)
migrate = Migrate(app, db)
#

look something* like this

ember rose
#
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)

if __name__ == '__main__':
    app.secret_key = "thisisasecretkey"
    app.run(debug=True)


API_KEY = 'fb84b8439094cc9d7a227150da1474d8'
API_SECRET = 'f25d18ad01e64c9887b5ca312f502787'
network = pylast.LastFMNetwork(api_key=API_KEY, api_secret=API_SECRET,)


shadow rock
#

block out the spotify stuffs

#

you just released spotify information into the open

#

edit your message to do this

ember rose
#

oopslol

shadow rock
#
SPOTIPY_CLIENT_ID=''
SPOTIPY_CLIENT_SECRET=''
SPOTIPY_REDIRECT_URI=''
#

alright

#

first off, you may wanna search up environment variables

#

to take care of that later

#

but also try this

#
app = Flask(__name__)
app.secret_key = "thisisasecretkey"
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)

if __name__ == '__main__':
    
    app.run(debug=True)


API_KEY = 'fb84b8439094cc9d7a227150da1474d8'
API_SECRET = 'f25d18ad01e64c9887b5ca312f502787'
network = pylast.LastFMNetwork(api_key=API_KEY, api_secret=API_SECRET,)
#

i'm assumign this just a toy project, but if you're going into production with this make sure you change your API_KEY, API_SECRET

ember rose
#

ok that worked thank you, this is a college project i dont give a shit about so yeah

#

but much appreciated

shadow rock
#

np

dense slate
#

Can someone explain what feels like a missing link in the Braintree setup for me? I understand that a customer_id is used to get a client_token, but nowhere can I find an explanation of how/why this works to make one.

I see docs about needing it and what the object looks like but like... if the buyer is buying something, do they have to create some kind of account for this id? Do I take it from their user account, therefore requiring all those values like first/last name, address, etc. when they signup on my website and then create it on their behalf? Could really use some clarification on this logic.

dusky osprey
#

@shadow rock I think there's a bug, actually I use both @jwt.expired_token_loader and @app.errorhandler but sentry is still reporting the exception

shadow rock
#

are you using flask_restful or flask_rest_plus

dusky osprey
#

Flask-RESTful==0.3.6

glossy atlas
#

What are good Django or Backend Projects Ideas for Beginners looking to build a portfolio?

native tide
#

I would guess anything that involved users logging in, having accounts they can change options in, and ways they can do things and have separate data thats all kept and normalized well.

I'm not an expert in this, but that's what my first thing was. Its a microblog that's only purpose is to show I can validate accounts, send out emails to change passwords. I imagine you could go further with some ways of storing payment methods and adding people to news letters.

If its for a portfolio, that sort of thing makes sense to me. But again, this is just my thinking. It not an experts.

tired root
#

@glossy atlas Learn django until you really know it, then look for projects to contribute to, on Github with your real name. That is how you get best attention

#

An employer would google your name and find you active on Github

#

When I was in the market for a new job, the employer actually printed out source code of mine and asked me to explain what it does during the interview

#

Even though I am a Sysadmin/Network Administrator and not a programmer

#

but he wanted to know if I am bullshitting or not

glossy atlas
#

@tired root So, If I feel confident enough (By following and copying enough tutorials) all I need to do to get started with real projects is to find a GitHub Django project that's open and in progress and work on it?

tired root
#

Yeah. Find something you find interesting and submit pull requests, fix bugs etc.

#

But don't submit bullshit

#

Many do that to fill their activity page

#

Contributing to FOSS is something professional employers value a lot

glossy atlas
#

@tired root Define "submit". What do you mean by that exactly?

tired root
#

sending pull requests

#

when you do a git push that is a pull request for the maintainer

glossy atlas
#

@tired root Oh, I get what you mean. Sounds like a better idea. I got tired of "Tutorial Hell"

tired root
#

I mean, I've learned flask by making a radio station out my pi

#

It's not yet fully done, but usable

#

Maybe find something you need to deepen your knowledge

glossy atlas
#

@tired root Well, I like Statistics and Web Development so I would like to do something like this:

https://www.freecodecamp.org/news/how-to-create-an-analytics-dashboard-in-django-app/ at some point.

freeCodeCamp.org

Hi folks!

Python, data visualization, and programming are the topics I'm profoundly
devoted to. Thatโ€™s why Iโ€™d like to share with you my ideas as well as my
enthusiasm for discovering new ways to present data in a meaningful way.

The case I'm going to cover is quite common: ...

tired root
#

then do it

#

new folder, git init and you are good to go

glossy atlas
#

@tired root The analytics project is too advanced for me (I think) but thank you for pointing me in a direction! ๐Ÿ˜

fossil swift
#

Is there anyway in Jinja2 to do {% if now-timestamp > 30 %} ? now is the current timestamp and timestamp is a timestamp from a database. I can't seem to do a greater than sybmol and a calculation at the same point. Any help?

native tide
#

Is there a way to have default selections for a select without adding a selected to it

#

Cause i dont want to have duplicates

native root
#

@fossil swift that code as written "works" for me--crashes because timestamp deltas are not integers so there's a typeerror

#

You might want to try (now - last).total_seconds() > 30

modest dirge
#

i know sell websites on fiverr

#

idk

#

i thought i could share

rustic pebble
#

I have a json file in this format:

{ date: { country: {'confirmed':, 'deaths':, 'recovered':}}}
#

I want to iterate in js through each of the countries

rigid laurel
#

can you paste slightly more of the format? e.g 2/3 countries

rustic pebble
#

Ye

rigid laurel
#

can you pastebin it so its easier to read?

rustic pebble
#

it is 12k lines json

#

I will try to post forlike 2 days

rigid laurel
#

just grab the top

#

the top like 100 lines or so should be enough

rustic pebble
#

eh top 500

#

This just spits out the total data for each day

#
async function global_numbers() {
    let data = await get_data();
    await console.log(data);
    count = 0;

    for (date in data) {
        count += 1;
        await console.log(data[date][0]);

    }
    await console.log(count);
}
#

But I cant get it to work for each country

valid cypress
#

Isn't this Python server?

rustic pebble
#

@valid cypress ^^^

valid cypress
#

Oh

rigid laurel
#

@rustic pebble

const jsonString = `{
    "01-22-2020": [
      {
        "Mainland China": {
          "ConfirmedCases": 547,
          "Deaths": 17,
          "Recovered": 28
        },
        "Hong Kong": {
          "ConfirmedCases": 0,
          "Deaths": 0,
          "Recovered": 0
        },
        "Macau": {
          "ConfirmedCases": 1,
          "Deaths": 0,
          "Recovered": 0
        },
        "Taiwan": {
          "ConfirmedCases": 1,
          "Deaths": 0,
          "Recovered": 0
        },
        "US": {
          "ConfirmedCases": 1,
          "Deaths": 0,
          "Recovered": 0
        },
        "Japan": {
          "ConfirmedCases": 2,
          "Deaths": 0,
          "Recovered": 0
        },
        "Thailand": {
          "ConfirmedCases": 2,
          "Deaths": 0,
          "Recovered": 0
        },
        "South Korea": {
          "ConfirmedCases": 1,
          "Deaths": 0,
          "Recovered": 0
        }
      }
    ]}`
let parsed = JSON.parse(jsonString)
console.log(parsed)
for (let [date, countries] of Object.entries(parsed)) {
    for (let [countryName, value] of Object.entries(countries[0])) {
        console.log(countryName)
    }

}
rustic pebble
#

@rigid laurel the dict that gets returned is returned using this:

#
return await response.json()
#

Do I have to use JSON.parse again?

rigid laurel
#

no, you'd just use the result of that

#

it might be slightly different for your object

#

but I'm pretty sure the use of object.entries is the solution

rustic pebble
#

In my case, which is a json reply from the server, what should I set the parsed as

rigid laurel
#

so I assume you have something like ```js
const myObj = fetch(stuff)

if so, you just want to use `myObj` as parsed
rustic pebble
#

I have this:

#
async function get_data(){
    let url = '/totaldata';
    const response = await fetch(url, {
          method: 'GET',
          mode: 'cors',
          cache: 'no-cache',
          credentials: 'same-origin',
          headers: {
            'Content-Type': 'application/json'
          },
          redirect: 'follow',
          referrerPolicy: 'no-referrer',
        });
        let data = await response.json();
        return data['Data']}
#

This is the flask backend

#
@app.route('/totaldata', methods=['GET'])
def totaldata():
    with open('totaldata.json', 'r') as file:
        jsfile = json.load(file)
        response = {'Success':'Data has been successfully obtained', 'Data': jsfile}
    return response, 200
#

jsfile is jsonfile

rigid laurel
#

so you'd replace parsed with the result of get_data() I think

rustic pebble
#

Right, that is what I thought from the start

#

let me try and I will update, thanks a ton!

rigid laurel
#

I have only tested it with the sample I posted above, so there might be issues with translating it to the big json

rustic pebble
#

So it works haha

#

If I wanted to access the keys inside each country name?

#

Would I have to open one more loop with the scheme of the previous?

rigid laurel
#
    for (let [countryName, value] of Object.entries(countries[0])) {
        console.log(countryName)
        console.log(value.confirmedDeaths)
    }```
rustic pebble
#

You. Are. God.

#

I have a question tho, how does it translate say deaths which is a key to an attribute?

rigid laurel
#

let [countryName, value] of Object.entries(whatever) is the exact same as doing for k, v in my_dict.items() in python, except instead of being a dict its a JS object

rustic pebble
#

ooh

#

I am not really good with JS, I mostly use it to pass requests from/to server and just change elements

rigid laurel
#

and with js objects, you can do both my_object.key, and my_object[key]

rustic pebble
#

Gotcha

#

Thanks a lot

rigid laurel
#

Thats the main thing you want to do with JS - its great for element manipulation, absolutely miserable for data manipulation

rustic pebble
#

I have got that impression from the moment I started using it for data manipulation

#

But I really dont like loading the server with unneeded things

rigid laurel
#

I have nightmares of NaN appearing everywhere

rustic pebble
#

Hahahaha

#

undefined is my trigger word

rigid laurel
#

yeah, showing NaN and undefined to the user is rubbish

rustic pebble
#

Overall JS is nice, but it gives me PTSD every time I use it to parse data from the server

#

Btw what is the equivalent of dictname.update() in js?

#

Oh nvm found it, it is push

modest dirge
#

what size of image should i use for css bc everytime i use an image it becomes blurry

#

and i heard that if u find a larger image it will be clear

rigid laurel
#

for what?

modest dirge
#

for my website

rigid laurel
#

for what on your website?

modest dirge
#

the background image

rigid laurel
#

Generally you want images to be as high resolution as possible

#

for a background you probably want it to look good on most screens which means 1920x1080 at least

modest dirge
#

k

#

thats all i needed the size

rustic pebble
#

I have included the file that has dict_to_array() inside it

rigid laurel
#

sounds to me like its due to the order in which you're loading things

#

but I could be wrong

modest dirge
#
 * {
     margin: 0;
     padding: 0;
 }

 header {
     background-image: url("startup-593327_1920.jpg");
     height: 100vh;
     background-size: cover;
     background-position: center;
 }

 .main-nav {
    float: right;
    list-style: none;
    margin-top: 30px;
 }

 .main-nav li {
     display: inline-block;
 }

 .main-nav li a {
     color: white;
     text-decoration: none;
     padding: 5px 20px;
     font-family: "Roboto", "sans-serif";
     font-size: 15px;
 }```
#

my code wont show the nav bar

#

it still shows as the list on the left

rustic pebble
#

Yup

#

It was I found it later @rigid laurel

tranquil robin
#

Hey guys, I am currently fetching some data from an API and I would like to use the data in a function, but I dont want to run the function inside the fetch() success part, I want to run the function in the main javascript body.
Is there anyway I can do that?

My example Code:

fetch("/api/test/", {method: "get"})
  .then(function(response) {
    return response.json();
  })
  .then(function(data) {
    //success  
    console.log(data);
  })
  .catch(function(ex) {
    console.log("parsing failed", ex);
  });

function somefunc(data){
    console.log(data);
}
// run function here
rigid laurel
#

so you want to be able to do something like

myData = fetchData(url)
processData(myData)
```? @tranquil robin
tranquil robin
#

yes

rustic pebble
#

Has anyone ever used chartjs?

#

I am trying to create a multiline chart and I am getting a weird glitch

tranquil robin
#

I tried using chartjs, but it wasnt very flexible so I moved to am4charts ๐Ÿ˜„

rustic pebble
#

Ah

#

well I fixed it

native tide
#

Anyone know any good was to minimize files

#

Like using other files to do methods

tired root
#

@native tide Are you using flask?

#

There is flask-minify for template output

#

otherwise there is uglifyjs and uglifycss on npm to use

dusky osprey
#

hi flask friends

reef zealot
#

Hello, if I want to build a Django web app that scrapes other websites with the data entered by the user, how would I go about this? I make the script, implement it in my Django app and when user clicks a button Django runs it?

tranquil robin
#

@reef zealot you would probably have a page with a form to request the relevant input from the user, and on submitting the form, you would use the input in your script

reef zealot
#

Yeah, but how will Django handle the script? Does it have to be async? Could I implement the script to run from the client side?

#

I'll explain what I'm trying to do here, I want to create a web app that searches for AWBs on different courier sites and the user can simply enter whatever awb he wants and would get the result

#

Running the script from the web app might get the IP blacklisted

rustic pebble
#

@reef zealot You can implement the script to run client side but youwill need javascript for that. Optimally you shouldn't make it async as Django already has a response management system which takes care of multiprocessing

#

You should treat each connection as a seperate instance of your server

reef zealot
#

Hmm thank you for the information, I'll just go at it in the weekend and see where I get

rustic pebble
#

Sure

glass sandal
#

Guys
Should I use django or flask?
(Not a beginner though)
And I've used both

vagrant adder
#

What usecase

rustic pebble
#

^^^

glass sandal
#

Like for making an online shop

rigid laurel
#

For an online shop id lean towards Django. You probably are gonna end up wanting most of the main features

vagrant adder
#

Yes, django is serve you better

tired root
#

Google is always complaining about my footer, for elements being too close together on mobile. While this snaps into a 1 column on mobile, I am not really sure what to do about it. Any ideas?

bleak bobcat
#

What does it look like on mobile ?

#

Google probably wants you to increase the vertical margin between elements

#

Imagine a fat finger, is there a chance it can click on 2 elements at the same time ?

tired root
#

in chrome menu

#

I can try to inrease the padding

#

or margin

bleak bobcat
#

Yea, links are just too close to each others

tired root
#

do you think 1vh is sufficient?

#

for google console to shut up?

undone copper
#

hi guys

bleak bobcat
#

I honestly don't know @tired root it's been a while since I've had time to have fun with frontend

limber laurel
#

Is flask login server or client side?

rustic pebble
#

@limber laurel server side ofc

rustic pebble
#

Has anybody used ChartJS I am having a problem displaying the correct labels in a line chart

limber laurel
#

Ok danke

ashen trench
#

can i serve my django static files from google firebase

#

ping me

jagged lark
#

Firebase storage? It looks like a cdn, so it is built for that @ashen trench

ashen trench
#

i can't find anything on that online

#

But there is a lib called pyrbase

jagged lark
ashen trench
#

yeah'

jagged lark
#

Yes, it is a cdn, it is built to serve statics

ashen trench
#

Firebase storage is essentially like S# buckets

#

S3*

#

But there is nothing much on it online for django if we look into s3 integration there is a lot of doc within the django official site

#

All i want is to serve my static files and media files with the firebase while my code is hosted on EC2

jagged lark
#

I mean, firebase isn't that used from what I saw, but you can just make a little script that uploads your statics to your firebase, put it under a cdn. subdomain, and use it inside your html, and you're golden

rustic pebble
#

I am literally getting trolled by javascript

#

but only 3 get on the diagram

#

wtd

rigid laurel
#

JS doesn't have sets

#

oh I see

#

yeah

#

you are being trolled

midnight vale
#

i know its outdates and they got an API out but i really wanted to finish this

#

i am making a twitter bot and having it just like a bunch every now and then i have come a good bit but cant make it work how it should even after using a bunch of methods (lost most solotions) but this is waht i got so far

## first beta 
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
import time

        ##

class TwitterBot:
    def __init__(self,username,password):
        self.username = username
        self.password = password
        self.bot = webdriver.Firefox()

    def login(self):
        bot = self.bot
        bot.get('https://twitter.com/login')
        time.sleep(3)
        email = bot.find_element_by_name('session[username_or_email]')
        password = bot.find_element_by_name('session[password]')
        email.clear()
        password.clear()
        email.send_keys(self.username)
        password.send_keys(self.password)
        password.send_keys(Keys.RETURN)
        time.sleep(3)


    def like_tweet(self, hashtag):
        bot = self.bot
        bot.get('https://twitter.com/search?q='+hashtag)
        time.sleep(2)
        for i in range(1,3):
            bot.execute_script('window.scrollTo(0,document.body.scrollHeight);')
            time.sleep(2)
            tweets = bot.find_elements_by_class_name('tweet')
            links = [elem.get_attribute('data-permalink-path') for elem in tweets]
            print(links)
            for link in links:
                bot.get('https://twitter.com' + link)
                try:
                    bot.find_element_by_class_name('HeartAnimation').click()
                    time.sleep(10)
                except Exeption as ex:
                    time.sleep(60)

ed = TwitterBot('xxxxxxxxxxxxxxxxxxxxxx', 'xxxxxxxxxxxxxxxxxxx')
ed.login()
ed.like_tweet('webdevelopment')
time.sleep(3)
#

the login function is fine untill half way of the like_tweet function

proper hinge
#

Twitter has an API

#

Your life will be much easier if you use it

#

There are even Python libraries for it

proper hinge
#

Oh you acknowledged that

#

Regardless, the way you're doing it is against their ToS and thus against this server's rules

#

Using the API wouldn't be

sly canyon
#

Does anyone have experience how to set up subdomains using Flask and Heroku?
.flaskenv

# ...
SERVER_NAME=myappname.herokuapp.com
# Have also tried SERVER_NAME=mydomain.com

routes.py

#...
@app.route('/', subdomain='sub', methods=['GET', 'POST'])

I have enabled:

heroku domains:add *.mydomain.com

Have added CNAME/ALIAS as such:

Host Record: sub
Points to: mydnstarget.herokudns.com
TTL: 14400

Still, I can't access sub.mydomain.com or sub.myappname.herokuapp.com It doesn't redirect to the desired route as I've specified in routes.py. Returns my endpoint for 404: @app.errorhandler(404).

bold bison
#

Guys I'm having an issue with django
urls.py

from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.urls import path
from . import views

app_name = 'blog'

urlpatterns = [
    #...
    static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT),
]

settings.py

AUTH_USER_MODEL = "blog.User"
MEDIA_URL = "/uploads/"
MEDIA_ROOT = os.path.join(BASE_DIR, "uploads")

ERROR

?: (urls.E004) Your URL pattern [<URLPattern '^uploads/(?P<path>.*)$'>] is invalid. Ensure that urlpatterns is a list of pa
th() and/or re_path() instances.

@native tide you should not include static inside the urlpatterns like above, it won't work.

#

but you can add your static files to urlpatterns like this:

#

urlpatterns = [] + static()

#

this is the correct way

native tide
#

I enjoy

dev_server_urls = [static(settings.STATIC_URL, document_root=settings.STATIC_ROOT),
                   static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)]

if settings.DEBUG:
    for static_url in dev_server_urls:
        urlpatterns += static_url
#

I have a question about User accounts that have two different profiles for options. Should I make a model of a base user class inheriting AbstractUser?

#

Django obviously

#

Or should I just use the one included?

#

The main thing that is not accepable about the default User is that there is no BooleanField for password confirmed in email, or... email must be unique in database

#

Which is just unacceptable

#

So I answered my own question. But what do you typically inherit User or AbstractUser ?

#

So Im reading that its considered best practice to write a new user class in the beginning by default in any Django project.

native tide
#

I'm having trouble saving my secret key as an environment variable. I cant even get bash to echo it out

#

if I do DJANGO_SECRET_KEY="<insert-key>" where <insert-key> is the key, I get bash: !8: event not found which I assume has to do with some escapings in the string. I get the same thing where I try to echo it as string literal or anything else.

native tide
#

I'm having so many problems this morning Im just going to sleep on them. I'll get to the next problems after I give time to hear back on this one

vague ruin
#

Hey, I'm building a REST API and I'm wondering how I should authenticate if user is allowed to use X api feature.
Currently I'm saving the hashed versions of passwords in database and when Im making a request I'm comparing the plain password to the databases hashed version.

Example: I'm sending a POST request to http://127.0.0.1:5000/customer to add new customer to db. The POST request would include the customer's information and the sender's user and password. All this in JSON. What I'm asking if this is a good way to handle this or should I do it some other way? I'm using Flask.

native tide
#

I was mistaken to think that I was ready to move on from Django. I'm getting stuck at some pretty basic things on my own project, with nothing to help me..

#

users/models.py

from django.contrib.auth.models import AbstractBaseUser

class User(AbstractBaseUser):
    """
    Account Holding Base User
    """
    email = models.EmailField(max_length=50, unique=True)
    date_of_birth = models.DateField()
    created_on = DateTimeField(timezone.now())
    email_verified = models.BooleanField(default=False)
    game_master_switch = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    EMAIL_FIELD = 'email'
    REQUIRED_FIELDS = ['date_of_birth']

the errors are too long for copypasta https://paste.pythondiscord.com/usexubogen.py
it definitely had to do with... I need to inherit all the things that AbstractBaseUser has into my User that I'm not specifying, because if you read that class, it has everything being said is missing.

valid cypress
#

I have question about FastAPI: Is possible to generate JWT key in shell, due I don't want register and login endpoints, due it's private API? Like in Django createsuperuser?

jagged lark
#

You could just make a custom entry point that generates a token, print it to stdout and exit

valid cypress
#

ok

#

But I have to find way how can discord.py bot and fastapi communicate on startup for key (in different servers).

#

But is good idea (security) to manually generate token and add this to bot and api .env file?

jagged lark
#

It should be fine as long you aren't working for the NSA

valid cypress
#

No, discord pokemon bot...

jagged lark
#

Should be fine then

agile wave
#

I'm trying to use Flask to build an API so that I can send and receive requests between a server script and multiple client scripts. However I'm unsure how to do this.

#
from flask import Flask

server = Flask(__name__)

@server.route("/")
def connection():
    return "Connected"

if __name__ == '__main__':
    server.run(debug=True)```
#

This is my server code for testing

#

I want to create a client that can receive and print the "Connected" string

#

Thank you ๐Ÿ˜„

jagged lark
#

The client will simply have to use a GET request on the root url

agile wave
#

How would I go about coding that in a client.py file?

#

Sorry if this is a dumb question, I'm completely new to using Flask and can't seem to find any solutions for this online

jagged lark
#

You can't use flask for that

#

Flask is just a way to create the server not the client

#

You'd have to use another library such as requests

#

!d requests

lavish prismBOT
#

This part of the documentation covers all the interfaces of Requests. For parts where Requests depends on external libraries, we document the most important right here and provide links to the canonical documentation.

agile wave
#

Okay thank you ๐Ÿ™‚

#

So, just to clarify, use Flask to make the server and then requests to make the client?

jagged lark
#

Flask to make the server, requests to interact with it

bold swift
#

Hey guys! Any ideas (+ maybe code examples) on how to deploy a Flask-Socketio app with docker?

wise monolith
#

Is there a connection protocol supported by a python library, which combines the "all-the-time connected" attribute of websockets with the "1 response to 1 request" structure from http?

limber orchid
#

what's the name of the {โ„… โ„…} markup you use in templates?

#

I'm trying to Google a thing but I don't know what to call it

#

ok I think I maybe found the name. jinja2?

stuck ether
#

Hey there, im a total noob so here comes a noob question: how i make this line to work

#

self.driver.find_element_by_name('password').send_keys(Keys.CONTROL + Keys.SHIFT + M)

#

i can send solo key signals

#

but i cant send them as a combo

#

and keys.m doesnt exist

#

so m is a string wich is m

#

yep

#

i want that a webpage goes intro phone mode

#

if u go on chrome, press control + shift + m it goes in that mode

#

but im not sure how to do that in code

#

brb need to get something

#

@ruby palm sry going to be afk for about 30 min

agile wave
#

How do I pass a variable through a Flask subroutine?

rigid laurel
#

You can use the flask global scope to do things

#

or you can use URL paramaters

agile wave
#
gameID = 0
games = []
players = ["Player"]

@server.route("/newGame")
def newGame():
    #Getting an error about gameID being referenced before assignment here
    Temp = game(gameID, players)
    games.append(Temp)
    gameID += 1
    return Temp.getGameID()```
#

How would I go about doing that?

rigid laurel
#

What exactly would want to pass into it?

agile wave
#

The global variable gameID above

rigid laurel
#

gimme a sec

agile wave
#

Nw, thank you

rigid laurel
#
from flask import g

g.gameid = 0 # can set this wherever or however you like
g.games = []
players = ["Player"]

@server.route("/newGame")
def newGame():
    #Getting an error about gameID being referenced before assignment here
    Temp = game(g.gameid, players)
    g.games.append(Temp)
    g.gameid+= 1
    return Temp.getGameID()
#

something roughly like that

#

There's the docs for that bit

agile wave
#

Perfect, thank you

rigid laurel
#

Oh, I missed a bit out. players should become g.players

agile wave
#

Yeah, don't worry about it aha

#

Thanks a lot, that's amazing ๐Ÿ˜„

#
Traceback (most recent call last):
  File "Server.py", line 159, in <module>
    g.gameID = 0
  File "Python\Python38-32\lib\site-packages\werkzeug\local.py", line 364, in <lambda>
    __setattr__ = lambda x, n, v: setattr(x._get_current_object(), n, v)
  File "Python\Python38-32\lib\site-packages\werkzeug\local.py", line 306, in _get_current_object
    return self.__local()
  File "Python\Python38-32\lib\site-packages\flask\globals.py", line 45, in _lookup_app_object
    raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context().  See the
documentation for more information.```
#

Any idea what that's about?

rigid laurel
#

OH I missed

#

something

#
def create_app():
    app = Flask(__name__)

    with app.app_context():
        g.gameid = 0 # can set this wherever or however you like
        g.games = []
        g.players = ["Player"]

    return app

You need to put that somewhere

#

and the somewhere will depend on exactly how you're running your code at the moment I think

agile wave
#

Oh right

#

How do I figure out where it needs to go?

rigid laurel
#

What does your structure currently look like?

#

is it all in a single file?

agile wave
#

Yes

rigid laurel
#

Can you just put the whole source in a pastebin

#

!paste

lavish prismBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

agile wave
#
from flask import Flask
from flask import g

server = Flask(__name__)

g.gameID = 0
g.games = []
g.players = ["Player"]

@server.route("/")
def connection():
    return "Welcome to BlackJack"

@server.route("/newGame")
def newGame():
    Temp = game(g.gameID, g.players)
    g.games.append(Temp)
    g.gameID += 1
    return Temp.getGameID()

if __name__ == '__main__':
    server.run(debug=True)```
#

That's all the Flask code I have rn

rigid laurel
#

replace your server = with server = create_app()

#

also, app is the standard name for what you currently have called server

agile wave
#

Okay yeah, is it worth changing to app?

rigid laurel
#

At this point it is yeah

agile wave
#

Okay

rigid laurel
#

if you need help in the future, it will make the helpers life easier

agile wave
#

Got it

#
from flask import Flask
from flask import g

def create_app():
    app = Flask(__name__)

    with app.app_context():
            g.gameID = 0
            g.games = []
            g.players = ["Player"]

    return app

app = create_app()

@app.route("/")
def connection():
    return "Welcome to BlackJack"

@app.route("/newGame")
def newGame():
    Temp = game(g.gameID, g.players)
    g.games.append(Temp)
    g.gameID += 1
    return Temp.getGameID()

if __name__ == '__main__':
    app.run(debug=True)```
#

So should have this?

rigid laurel
#
from flask import Flask
from flask import g


def create_app():
    app = Flask(__name__)

    with app.app_context():
        g.gameid = 0  # can set this wherever or however you like
        g.games = []
        g.players = ["Player"]

    return app


@app.route("/")
def connection():
    return "Welcome to BlackJack"


@app.route("/newGame")
def newGame():
    Temp = game(g.gameID, g.players)
    g.games.append(Temp)
    g.gameID += 1
    return Temp.getGameID()


if __name__ == '__main__':
    app = create_app()
    app.run(debug=True)
agile wave
#

Getting an error of "app" not being defined on the line "@app.route("/")"

rigid laurel
#

I'm trying to figure out the right way to do it

#

I've done this before and it wasn't difficult

agile wave
#

Yeah nw ๐Ÿ™‚

#

Really appreciate the help, sorry if I'm being a pain

rigid laurel
#

ahh - the way I told you to do it isn't the way I've done it before. This should work

from flask import Flask
from flask import g

app = Flask(__name__)


@app.before_request
def before_request():
    g.gameID = 0  # can set this wherever or however you like
    g.games = ['fasd']
    g.players = ["Player"]


@app.route("/")
def connection():
    return "Welcome to BlackJack"


@app.route("/newGame")
def newGame():
    Temp = game(g.gameID, g.players)
    g.games.append(Temp)
    g.gameID += 1
    return Temp.getGameID()


if __name__ == '__main__':
    app.run(debug=True)
#

A trimmed down version of that runs for me

agile wave
#

Works now

#

Thanks so much

#

Can't return integers for some reason though

#

Had to change one of the lines to "return str(Temp.getGameID())"

rigid laurel
#

So I didn't really think about what you were doing til now. The globals will run for this without error, but I don't think it will do what you want. If you want to store data between multiple requests (which it seems you do), then you need to store that in some other wayy. The standard way would be with a session, with a database, or with some kind of cache like redis

#

The easiest one of those is with a session

agile wave
#

How easy is it to make a session?

rigid laurel
#

Not too difficult, its a very similar idea to the g thing

#

flask-session is the normal way

#

Oh wait

#

there's a session object in flask

agile wave
#

Do u know how to use it?

sly canyon
#

[FLASK]
Does anybody knows how can point my 'static' folder to an URL endpoint that doesn't match my app SERVER_NAME? My app runs on Heroku.

Domain: mydomain.com
HerokuServer: my.herokuapp.com

Flask SERVER_NAME is set to mydomain.com in order to build subdomains such as sub.mydomain.com. My domain is set an ALIAS/CNAME to point * .mydomain.com to my.herokudns.com.

But, because of that, when I use url_for('static') it's trying to search files on my.domain.com instead of my.herokuapp.com.

Can anybody help me on that?

midnight vale
#

does anyone have a webdev server?

#

DMs open

weary acorn
#

im deploying my flask app to heroku

#

it builds sucessfully

#

but when I go to the link it says its broken

#

anyone want to look at my procfile/requirements/runtime/aptfile

#

runetime.txt: python-3.8.2
Procfile:

worker: set FLASK_APP=app.py 
flask run

probably wrong^

Aptfile: git

requirements.txt: git+git://github.com/lovvskillz/python-discord-webhook.git

#

please ping me when someone responds

leaden lantern
#

@weary acorn remove that flask run

weary acorn
#

ok

#

thats it?

leaden lantern
#

and send me scrnshot of Logs of heroku

weary acorn
#

I dont have the heroku cli

leaden lantern
#

is your bot online?

weary acorn
#

I doing it through the website

#

no

#

i try to upload it

#

it says its deployes

#

but when I go to the link

leaden lantern
#

ohkk i will help you

weary acorn
#

it says application error

#

but ik its not the code or html

#

cause it works on local

leaden lantern
#

is your bot running perfectly in ur system

weary acorn
#

yep

leaden lantern
#

install heroku cli

weary acorn
#

how

leaden lantern
#

you're using windows?

weary acorn
#

yep

leaden lantern
#

download it

#

and install

weary acorn
#

ok

#

ok done

#

@leaden lantern I did that

leaden lantern
#

open command prompt as admin

weary acorn
#

ok

#

system32?

leaden lantern
weary acorn
#

i have

leaden lantern
#

ohkk

weary acorn
#

wait it says system32

#

is that right

leaden lantern
#

yes

weary acorn
#

the directory

#

ok

leaden lantern
#

type cd dir..

#

dir : your bot directory

weary acorn
#

my bot is in my local disc/users/my user

#

should I go to that

leaden lantern
#

cd c:/users/myuser/folder

#

like this

#

where your .py file exists

weary acorn
#

ok

#

how do I ls

#

list files

#

ls doesnt work

leaden lantern
#

wait

#

come on Voice i will stream you

#

Code/Help

weary acorn
#

ok but I dont have mic

leaden lantern
#

i also will not speak too

weary acorn
#

ok

leaden lantern
#

ohkk

#

calling you DM

weary acorn
#

ok

native tide
#
class User(AbstractUser):
    """
    Account Holding Base User
    """
    email = models.EmailField(max_length=50, unique=True)
    date_of_birth = models.DateField()
    created_on = DateTimeField(timezone.now())
    email_verified = models.BooleanField(default=False)
    game_master_switch = models.BooleanField(default=False)  # TODO: True to Designate a GameMasterProfile

    USERNAME_FIELD = 'email'
    EMAIL_FIELD = 'email'
    REQUIRED_FIELDS = ['date_of_birth']

    def create_superuser(self, email=None, password=None):
        user = self.create_user(
            email=email,
            password=password,
            is_staff=True,
            is_admin=True
        )
        return user

after making these migrations, I try to createsuperuser
I get though asking for email, dob, password, but I always get this

  File "Projects/shell_hacker_game/venv/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 189, in handle
    self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
TypeError: create_superuser() missing 1 required positional argument: 'username'

I dont need a username. An email is all I need.

#

I can only assume its referring to a method defined somewhere else

#

Man, I'm getting tired of Django tbh

#

Everything that you do in this framework is writing over something else and there is no joy in it.

#

I'm sure that it gets products out quickly.

#

I'm losing interest in digging in these docs in my spare time to change default functionality though

#

I could feasibly make the username = the email in the code but then Im keeping duplicate data because im tired of digging in Django code lol

#

I think what I have to do is create AbstractBaseUser instead of just AbstractUser but I have to do a lot of copying the default and only changing it where I want.

hasty turtle
nova tulip
#

Random question but does anyone know of a good guide for implementing a rest client? But not just an example tutorial where they make one request but like an enterprise level system design guide?

native tide
#

I may very likely throw my django project in the trash and start on flask.

#

Just to see how it might be different than this.

elfin solstice
#

Using django, trying to make a website, part of which allows users to submit text to be displayed. Problem: I obviously don't trust my users, so I want django's autoescape, however I do want them to be able to insert new lines. When I just do .replace('\n', '<br>') on their input, django escapes the <br> and displays it literally. How can I change that?

agile wave
#

!paste

lavish prismBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

agile wave
#

Hi, I'm trying to create a multiplayer blackjack game with a server that can connect with multiple clients so that they can play against each other.
As of now, I have created a local one player game and am attempting to use Flask and Requests to rewrite the code into a client and server script.
However I'm unsure of where to start with this as I'm very new to using the Flask library.

#

All help is really appreciated, thank you ๐Ÿ˜„

rustic pebble
#

@agile wave you should probably use a socket based library

agile wave
#

I've tried but the ones I've found are too low level to be useful

rustic pebble
#

Wdym?

agile wave
#

I've had to spend ages coming up with my own header system and I needed to make sure that both scripts were receiving/sending the required data at the same time and it was too easy for them to go out of sync

#

With Flask, I can see that I'll be able to send a request and then get something back based entirely on that since it's stateless

rustic pebble
#

Yes but opening sessions with flask isnt as easy

agile wave
#

What would you suggest?

rustic pebble
#

Tbh, although I havent used it much

agile wave
#

I just feel like it's too much work to set that up for what it does

#

Is there not an easier way to just send variables between programs over the internet?

vagrant adder
#

you are looking for a socket

agile wave
#

I've used sockets, there's too much overhead and it doesn't do what I actually want it to do

#

I need my client to send something to the server, then the server runs a function based on what was sent

#

Sockets just take what was sent as a variable and I can't see a way to use that to call different functions without almost creating my own library

rustic pebble
#

If that is all you want then flask is the way to go

#

@agile wave

agile wave
#

Right, yeah

#

Sorry for being a pain

green echo
#

is it possible to capture the client's webcam on send over to python using flask/socket.io?

rustic pebble
#

@green echo I gues

#

guess*

#

But you need to use javascript for that, and use sockets not flask

green echo
#

yeah sure

#

ok now for the question

#

is it possible how to capture the client's webcam on send over to python using flask/socket.io? javascript and sockets?

#

@rustic pebble ?

rustic pebble
#

Not really sure how you would pass it to the server-side, aiohttp should be the way to go

green echo
#

umm

#

i have already read that article

rustic pebble
#

then what is the problem?

green echo
#

passing it to the server side

rustic pebble
#

Hmm

#

That would be difficult indeed

green echo
#

i want it to pass the frames like

#

in a perfect world example:

#

send_server(video.read())

rustic pebble
#

I know what you want to do

#

I really haven't done any live feed client->server

green echo
#

okay good

#

bummed

rustic pebble
#

But this is getting me nervous because an aspect of my project has this

#

actually 2 aspects

#

If I were you I would find any way I could and then just make a module out of it so I can actually just do send_server(video.read())

green echo
#

lol

#

so, what now?

rustic pebble
#

I am not sure you would want to build it with python backend at all

#

Look up feathers.js

dense mica
#

im creating a web app using django
but how to save the webcam pics and upload it to the database?
<input type="file" accept="image/*" capture="camera"> this doesnt work for pc!

green echo
#

@dense mica you realize your question is the about the same as the question i asked right before you

dense mica
#

when?

#

ok now i see

green echo
#

yeah

dense mica
#

hey i have link

green echo
#

so notice me if you find the solution

#

ima using flask tho

dense mica
#

but it is written in spanish and hard to understand

#

okie

#

the codes written in spanish*

green echo
#

lmao wat

dense mica
#

haha it may work for django

#

dont know about flask

green echo
#

all i need to know is how to send an image from webcam to python using sockets

wicked basalt
#

Hi can anyone help me locate an XPath with Selenium based on a td ?
This doesn't seem to work
driver.find_element_by_xpath("/html/body/div/main/div[2]/div[1]/div[2]/div[3]/table/tbody/tr[2]/td[text()='Rachel']/button")

sly canyon
#

@wicked basalt what's the website and element

wicked basalt
sly canyon
#

Is the button you want to click

#

Text identifiable?

#

I mean, I can see that the tr, td and button classes are the same across the application

#

So you can't identify one from the other based on the class

#

Can you do it by the text within?

#

If you can, you can try something like:
driver.find_element_by_xpath("//button[text()[contains(.,'some string')]]")

#

driver.find_element_by_xpath("//button[text()='some string']")

#

If the text is not within the button stuff, you have to match it to the element that has it and then continue your search using a ////

#

driver.find_element_by_xpath("//tr[text()='some string']/button") or something like it

quasi kelp
#

hi there

#

I was wondering what the top discords/irc's are for getting django help?

#

please ping me when you reply

wicked basalt
#

@sly canyon Yes, I would like to click on the button that has in td "!Women Art Revolution" for example

sly canyon
#

Try the options above until you get the right element

#

Make small adjustments if neccessary

wicked basalt
#

And yes the text is not within the button stuff, so I have to match it to the elment that has it

#

What's the difference between / and // ?

#

I tried driver.find_element_by_xpath("//tr[text()='some string'] but I get the NoSuchElementException error ๐Ÿ˜ฆ

sly canyon
#

@wicked basalt you have to make adjustments

#

Only you have access to the DOM

#

'some string' has to be replaces

#

*replaced

#

that's why it's called 'some string'

wicked basalt
#

Yes I did replace it with "!Women Art Revolution - A Secret History"

#

But it didn't detectyi t

#

I think one of the problems is that the button and the td are in the same hierarchy

sly canyon
#

@wicked basalt so driver.find_element_by_xpath("//tr[text()[contains(.,'!Women Art Revolution - A Secret History')] is not working?

#

when you use text() = it will only work if the text is exactly equal.

wicked basalt
#

I just tried and it does not work :/

#

again*

#

And I put an implicit wait in case too

rustic pebble
#

Anybody know why I am getting import errors in my flask app?

#

This is my file structure

#

This is the Idea class

#
from main import db

class Idea(db.Model):
    __tablename__ = "ideas"

    id = db.Column(db.Integer, primary_key=True)
    title= db.Column(db.String())
    post_body = db.Column(db.String())
    author = db.Column(db.String())

    def __init__(self, title: str, post_body: str, author: str):
        self.title = title
        self.post_body = post_body
        self.author = author

    def initiate(self):
        db.create_all()
sly canyon
#

@rustic pebble Have you initialized the DB? db = SQLAlchemy(app)

rustic pebble
#

Yup

sly canyon
#

Paste the first lines of your main.py

rustic pebble
#
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
from controllers.database import Idea
from helpers.user_post import Post
app = Flask(__name__)
sly canyon
#

from controllers.database import Idea

rustic pebble
#

yes

#

What?

sly canyon
#

I'm thinking

#

Chill :)

rustic pebble
#

Ah

sly canyon
#

Not sure

#

Try to replace Idea with *

#

from controllers.database import *

rustic pebble
#

ok sec

sly canyon
#

And let's see what happens

rustic pebble
#

same

sly canyon
#

but now on a different file

#

user_post.py

rustic pebble
#

ok

sly canyon
#

I usually import the db classes after the app has been initialized

rustic pebble
#

xd wtf

sly canyon
#

Example:

from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_moment import Moment
from flask_babel import Babel
import datetime
from config import Config

#  Deploy
app = Flask(__name__, host_matching=True, static_host='maxiimoveis.herokuapp.com')

app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
moment = Moment(app)
babel = Babel(app)

from app import routes, models, forms, email, errors, logs, contact
rustic pebble
#

let me try again then

sly canyon
rustic pebble
#

Same error

sly canyon
#

That's because if I try to import it before instantiating the app, it doesn't work