#web-development

2 messages · Page 74 of 1

late fjord
#

@flint breach can I ask you something

#

I wanna know how much a quora clone in django can cost, and how much an ecommece website costs, I mean if I wanna make one how much I can sell it for

#

@flint breach I am asking you cuz you may have a lot of experience in freelancing

flint breach
#

i work at a company, so i wouldn't really know

#

never worked as a free lancer

#

but a question of how much can a clone of "X" cost can vary highly

#

first of all, depends if there are buyers interested

#

second, you can make a clone of instagram

#

but it's not really...like instagram if you know what i mean

late fjord
#

I just wanna get an idea, if you make one how much would you sell it for

#

10k

#

???

flint breach
#

Ehh, i couldn't tell you, i don't know myself

#

as i've said, don't have freelancing experience 😛

late fjord
#

is it hard to make one

flint breach
#

depends on what scale

modest scaffold
#

@late fjord i have already done all that

#

@flint breach i have put an extend i didnt show the full code because i didn't think it was necessary

flint breach
#

aha

#

tried reseting cache?

modest scaffold
#

how do i do that

flint breach
#

google how to reset browser cache

#

any luck?

modest scaffold
#

didnt seem to work

#

@flint breach

flint breach
#

hmm

modest scaffold
#

this is annoying

#

when i go on the webpage and inspect element it appears but it has no affect

flint breach
#

oh, then it has loaded sucesfully

#

probably something got overwritten in the css hierarchy

limpid jewel
#

Hi!, I have question, how can i get content error message from my response when i have 500 status code? I Wrote my midlleware for this action but in response.content i have all html code with error and in response.reason_phrase field i have only short message Server error

class LoggerMiddleware:
    def __init__(self, get_response=None):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        if response.status_code == 500:
            print(response.content)
        return response
native tide
#

Easiest way to deploy flask app with mysql db on apache linux server ? I never did that was working on heroku and AWS in general..

late fjord
#

@modest scaffold try this {% block 'head' %} #put your title and css link here, make sure it is above the other one {% endblock %}

#

@modest scaffold instead of block title and block addition....

modest scaffold
#

ok will try this later ill keep you updated if that okay

late fjord
#

totally fine

balmy shard
#

Does anyone know if I can host a flask site in tor?

#

/with tor

late fjord
#

imagine we have two apps, we want to use the same main template on both apps in django, please help

modest scaffold
#

@flint breach that cant be the case because im not overriding anything

#

well i dont think i am

flint breach
#

check in dev console

#

either it's cache or that, since you said you checked and it's on the site

#

the css file

#

developer tools are your friends

late fjord
#

@modest scaffold it didn't work ??

low blade
#

is ASP Core something that's worthwhile to learn?

modest scaffold
#

i havent tried it yet bc im a bit busy with something else

zealous siren
#

Beachtastic, only if you want to do more C# development

low blade
#

i figured. i just wasn't sure if it was something i should actively try to learn since idk what the trend is atm

zealous siren
#

If you know C# and want to continue using it, it’s very nice.

rigid laurel
#

ASP and Javay Springboot stuff only seem worth it if that's what you gotta do for a job

zealous siren
#

It’s very capable

#

And fast

low blade
#

im casting a wide net at this point (career-wise), so i think i'll do a small project on it to get familiar with it lol

zealous siren
#

We build rest API at work with it for our Angular front ends

past cipher
#

Flask:

How can I specify an API key inside init and use inside routes?

#

Key will update every so often, so I would rather create it inside init which is pretty empty

### init 
api_key = '11233'
## routes.py
uri = 'domain.com/apikey={keyhere}'
late fjord
#

Django:
Do I have to create a template file in each django app?
@mellow briar @modest scaffold @flint breach @native tide

flint breach
#

don't ping everyone please

modest scaffold
#

yes

flint breach
#

just ask your question, you'll get an answer

modest scaffold
#

you do need to create a template file for each app but you could do one main template file

flint breach
#

you don't actually

modest scaffold
#

and dont ping people unless they're engaged in the convo

late fjord
#

yes

flint breach
#

depends on what you need

late fjord
#

If I create a template file in the base dir will I be able to use it

#

in all the apps

flint breach
#

yea

#

it's just a convention, of course it's prefered that unique templates of an app go into the app directory

#

but something that's shared throughout the project can be in a shared template directory, so to speak

late fjord
#

thanks

mellow briar
#

what do you mean by a "template"?

late fjord
#

an html file in django I guess

mellow briar
#

no

late fjord
#

so what

#

???

mellow briar
#

you only need to do that if you will be rendering that view

late fjord
#

do what

mellow briar
#

if you are building and API with django rest framework or graphene geaphql (or other similar framework) you will not need to write html code

#

which is the recommended

#

to separate front and back end applications

flint breach
#

not really recommended, a different style definitely (SPA and the like)

mellow briar
#

its more scalable tha monolotic applications and expansible to mico service integrations

#

but anyway, idk waht the ideia of the mate here

flint breach
#

most people don't really need something to be google scalable

mellow briar
#

i guess you shoud take a look of how these things works together

flint breach
#

django scales well

zealous siren
#

I wouldn’t use Django for RestAPI unless you already have Django site

late fjord
#

I don't what you guys are talking about cuz I haven't gone through these details yes and the rest freamework

mellow briar
#

thats a matter of point of view. These was mine, im getting back to work here, so good study yall 😄

zealous siren
#

Look at Flask or FastAPI instead

late fjord
#

I have been using django for a month and a half maximally

flint breach
#

I wouldn’t use Django for RestAPI unless you already have Django site
@zealous siren disagree

#

or maybe not, depends 😄

zealous siren
#

Django is heavy, Rest API are not. No need for all that weight

late fjord
#

If I want to create a website where you can post, ask questions.
Is it good to put them all inside one app called app
Or maybe put posts inside and app and questions in another one

rigid laurel
#

Django for a rest api gives you the advantage of a phenomenal ORM

#

it's annoying that it comes with the rest of the Django baggage though

#

someone should figure out a way to add the Django ORM to FastAPI

#

then FastAPI would be the best tool going

late fjord
#

@rigid laurel please answer my question

cold anchor
#

sqlalchemy is the agnostic equivalent to django orm

#

(for SQL)

dapper tusk
#

ye, django is not the only ORM

flint breach
#

you can put it all in one app, if it ties togheter well

#

if it makes sense that it's togheter, put it togheter

late fjord
#

but which is better

dapper tusk
#

either is probably fine. I would lean towards more apps

rigid laurel
#

SQLAlchemy is rubbish compared to Django's ORM

cold anchor
#

hard disagree, SQLAlchemy is great

rigid laurel
#

Django's ORM blows SQLA out of the water in terms of usability

#

Tying together Flask+FlaskSQLALchemy+Alembic+Marshmallow to get a Flask API going is just a massive PITA. Someone combining all of that to make it more cohesive would be so much nicer

cold anchor
#

lol the reason they exist separately is to give you a choice of implementation

#

if you like all those tools together just make a project template

flint breach
#

each orm has it's own quirks and pros/cons

#

says one is rubbish seems harsh

cold anchor
#

☝️

rigid laurel
#

I hate the ikea feeling - and I guess the cookiecutter stuff is a goodish solution. But my experience with Django's ORM is that it's nicer in almost every single aspect, and having a single source for information about the entire system (i.e the Django docs) makes it so much easier when you're not super experienced with all the parts

cold anchor
#

having a single source for information about the entire system (i.e the Django docs)
SQLA also has docs

rigid laurel
#

SQLA's docs are not what I'd call good examples of documentaion

#

just looking at something like m2m relationships, they're so much easier to deal with in Django

cold anchor
flint breach
#

meh, down to preference i think

#

if you're not gonna use django, then it's orm is outa the question anyway

#

🤷‍♂️

cold anchor
#

true, I don't like that django hides the implementation details

flint breach
#

to each his own, i love that, (when im doing most things)

#

but when i have to customize something or extend it, that abstraction can definitely become a real pain

#

then again, python is C with hidden implementation details 😛

rigid laurel
#

Sounds to me like you like doing work for the sake of doing work

#

I can understand a database schema from a theoretical perspective, I don't necessarily feel the need to get too close to the actual SQL though

#

Django hiding a link table from me is fine in my books

flint breach
#

when writing deep nested/complex queries though, that's when the orm is a pain in my ass

bleak bobcat
cold anchor
#

I like knowing how my ORM is querying my tables. I have experience with SQLAlchemy and how it works so I like it, I'm sure I'd like django's orm the same once I got to know it, but the docs don't seem to expose how they're querying the data

flint breach
#

under every query you make, django exposes a query attribute to every queryset you make, that's basically the constructed sql statement

#

it's preety sweet

cold anchor
#

that sounds nice

rigid laurel
#

I've heard bad things about ORMs and complex schemas - but right now I'm lucky enough to never have dealt with a complex schema outside of raw SQL itself - so I guess I can't speak for that too much

#

But Django's model of querying feels much more natural/expressive than SQLAs way

flint breach
#

agree with simple queries, strongly disagree with complex ones

rigid laurel
#

been too long since I touched either to give a specific example

#

but I really feel like for most standard enterprisey schemas - Django is fine

flint breach
#

oh, sqla, thought you meant raw SQL in general

#

nevermind then 😄

rigid laurel
#

if your system is big enough that complex schemas are a problem - then I think I'd be sick of Python as a whole and just want to redo it as microservices or in Kotlin

flint breach
#

agreed tbh

cold anchor
#

that sounds like trading out one set of problems for another to me

rigid laurel
#

well - rebuilding a system is rarely a solution yeah, but starting off in Kotlin seems like it would be much better

cold anchor
#

in general though, trading out one tool for another is just switching the problems you'll have

#

mongo vs sql, django vs flask, GCP vs AWS

flint breach
#

ehh, relational vs non relational solve completely different problems

cold anchor
#

not really, most dbs can switch them out without much difference

#

if you have relational data, then yeah, don't use nosql

flint breach
#

oof, strong disagree, completely different scalability setups, sharding and fragmenting is trivial in nosql, redundancy difference, CAP, data schemes itself

rigid laurel
#

Mongo vs SQL seems pretty clear cut to me

cold anchor
#

this is what I mean though, sql vs nosql can be swapped out for most db schemas, you're just trading the problems (you listed administration, but schema setup and query optimizing are also some problems you'd trade)

zealous siren
#

Postgres has Citus for scaling

rigid laurel
#

The solution to every problem seems to be Postgres

zealous siren
#

I don’t use Postgres

rigid laurel
#

Well - you live in Azure land right?

zealous siren
#

Yep

rigid laurel
#

and I'm guessing MS have some proprietary thing

zealous siren
#

They do

rigid laurel
#

MSSQL+scaling fun

zealous siren
#

But they have very strong Postgres support

#

In fact, Microsoft owns Citus

hollow glacier
flint breach
#

afaik, drf support is added into the lib itself, so yes.

hollow glacier
#

Thanks

#

But it should work with templating aswell right?

flint breach
#

what do you mean?

hollow glacier
#

Like, I want to use django-filter with ajax in vanilla django

flint breach
#

im still not sure i follow

#

you can filter in with regular querysets, and before you serialize to deal with api requests

hollow glacier
#

The thing is that I'm not building an api

#

I'm using templates

flint breach
#

you said you're using ajax

hollow glacier
#

Yes

#

I'm using ajax to get some stuff

flint breach
#

that means you're using an api

#

oh, but not your own api?

hollow glacier
#

No

flint breach
#

aka an api you can't control?

#

then you can't use it, no

hollow glacier
#

I'm mixing templates with some api-ish endpoints

flint breach
#

you're not recieving models, you're recieving json data

#

if you control the api endpoints, you can use django filters to sort

#

but then again, don't know if you need to

native tide
#

hey all -- trying to verify a password input against db entry however it always returns "The password does not match the supplied hash". I use argon2 against the input with the same parameters as the first except the salt, since argon2 by default randomly salts each time, thus the two entries never matching. Should I be using the same salt, or am I misunderstanding how the verify function works? I thought this may be the right channel (since it's webdev related), however if I should move this to security instead pls let me know! If any additional info is needed I'll gladly add to this. c:
using py3.8, tornado, mysqldb and argon2id.

flint breach
#

The salt should be the same

blazing jetty
#

I'd like to close window after oauth2 with flask, can I do that?

#

javascript can't :/

static wind
#

hey all, i'm using flask to process data from a post request from ajax in JS script, how do i process lists?
i'm sending the list like this:
weblogs: automodWeblogs where automodWeblogs is an array of JSON objects (because this is in the JS code)
i'm processing the data sent by using request.form but i've also tried request.form.to_dict().
Whenever I print out the data i receive, it prints in a form like this:

'weblogs[0][user]': ['MrHouck#6969'], 'weblogs[0][time]': ['Sat, 25 Jul 2020 17:36:29 '], 'weblogs[0][action]': ['automod.bannedWord.remove'], 'weblogs[1][user]': ['MrHouck#6969'], 'weblogs[1][time]': ['Sat, 25 Jul 2020 17:36:29 '], 'weblogs[1][action]': ['automod.bannedWord.remove']

How do I fix this?

#

the issue being that it's formatting like [weblogs][0][user] whereas it should be like weblogs[{'user':'MrHouck#6969', 'time':'Sat, 25 Jul 2020 17:36:29 ', 'action':'automod.bannedWord.remove'}]

native tide
#

@flint breach thanks for the suggestion, appreciate the help; while that would work, I went back to the docs to reread (thought maybe I did misunderstand) and turns out the verify function of a2 uses the stored salt from the hash when comparing against the input, so there's no need to hash the input from the form, as it does it on it's own.

proud igloo
#

hello guys

#

say the above was in a different file

#

__name__ would be different right?

#

if I do tracer = trace.get_tracer("__main__") this also returns None

#

even though it has been ran before in manage.py

#

how do I share this tracer?

#

can anyone tell me what:

Can't instantiate abstract class TracerProvider with abstract methods get_tracer

#

means?

#

why is that happening

native tide
#

can anyone tell me what:
@proud igloo you have to implement the method get_tracer, or extend that abstract class and implement the method.
Abstract classes are not meant to be instantiated (hence the creator defined the class abstract).

proud igloo
#

but when I called it before it worked fine!

#

that is what I am so confused about

#

in def main():

#

I am trying to copy this example

#

what is the difference between putting it in a main and putting at the top of an imported file?

viral ocean
#

wdym in a main

#

python doesn't have main functions

proud igloo
#
if __name__ == "__main__":
    main()
def main():
cyan wolf
#

Yo

viral ocean
#

You can do that, but it is a little silly, why not just put whatever you were gonna put in main() in that if statement

proud igloo
#

I didn't write it

#

django did 😛

dapper tusk
#

the reason behind this is so that variable within the main block does not get put in the global scope.

dusky notch
#

Hello everyone

twilit zenith
#

hey, I was wondering what was Apache and Nginx, i saw few people talking about it in #cybersecurity, if I want to deploy my Django Rest API, how do I do that?

proud igloo
#

for example I am just doing this:

jaeger_collector_host_name = os.environ.get("JAEGER_COLLECTOR_HOST_NAME", False)
trace.set_tracer_provider(TracerProvider())

if not jaeger_collector_host_name:
    # print tracer
    trace.get_tracer_provider().add_span_processor(
        SimpleExportSpanProcessor(ConsoleSpanExporter())
    )
else:
    # jaeger tracer
    jaeger_exporter = jaeger.JaegerSpanExporter(
        service_name="App",
        collector_host_name=jaeger_collector_host_name,
        collector_port=14268,
    )
    trace.get_tracer_provider().add_span_processor(
        BatchExportSpanProcessor(jaeger_exporter)
    )

application = get_wsgi_application()
application = OpenTelemetryMiddleware(application)

and I get

TypeError: Can't instantiate abstract class TracerProvider with abstract methods get_tracer

viral ocean
#

TracerProvider isn't meant to be instantated by itself, it is an abstract class

#

you need to use a subclass of TracerProvider

#

so my guess is the docs are outdated

#

Oh wait looks like there is two different things called TracerProvider in two different places

#

what do your imports look like

#

@proud igloo

proud igloo
#

from opentelemetry.sdk.trace import TracerProvider

#

is that wrong?

#

ahh!!

#

that was it

#

thank you so much!!

plain axle
#

i'm trying to make custom error views in django

#

i'm settings the handlers in my urlconf

#

and i have DEBUG set to False

#

but whenever i go to a page that would give me a 404, it's using django's default 404 view instead of using the custom one that i specified

#

i'm setting the 404 view in my urlconf as this

handler404 = "uploader.views.err_not_found"
#

and the view is

def err_not_found(request: HttpRequest, exception):
    payload = {
        "message": "The requested resource was not found on the server."
    }

    return JsonResponse(payload, status=404)
#

i see no reason why it's displaying django's default 404 view

#

instead of using the one i provided above

distant trout
#

is it possible to get a BLOB image data from sqlite and display the actual image? Using flask.

#

I have the image blob data saved in the database, but am clueless how to show it back to the user

#

When i try to show it on jinja, it gives me this weird b"

#

Also by the way, the user can upload the image and it is saved in my static directory

mellow tide
#

hey, I was wondering what was Apache and Nginx, i saw few people talking about it in #cybersecurity, if I want to deploy my Django Rest API, how do I do that?
@twilit zenith they are web servers, the things that actually run your code

merry geode
#

@distant trout It seems the image is base64 encoded. Just look up how to encode/decode base64 in Python

uncut spire
#

for a flask app in an AWS VPC, is there an easy way to enable CORS for any other application hosted in the VPC?

#

is it as simple as allow * and the VPC does the rest?

acoustic oyster
#

Howdy friends, I have a Django app/api. It especially has blog posts, but these posts need to maintain their formatting (i.e tabbed lines, spaces, line breaks etc.) So it should be as easy as writing the content in microsoft word, then pasting the result in a text field. this data needs to then be sent via api. Any ideas on how to accomplish this?

thorny geyser
#

markdown?

acoustic oyster
#

Ty, I answered my own question. I was using markdown, but it was unreasonable for the user to know how to use it.

I realized the <pre> tag in html is made just for this and django/django rest api preserve this formatting, so the only solution was on the front end.

wind walrus
#

I have a flask app up and running on Heroku, using gunicorn

#

How do I serve static files?

native tide
#

look for s3

wind walrus
#

I read about Nginx/Apache/Amazon S3, do they do the same thing?

#

Nginx is free whereas Apache/S3 are not?

#

Apache/Nginx isnt for static files right?

sturdy pike
#

Is anybody out there

stone wren
#

what is the equivalent of django rest serializer source attr in flask marshmallow?

native tide
#

If I have a rest API in DRF that allows users to join events, what would be the best way to not allow any more users in an event when max capacity is reached? A validation method in the serializer class? Or is it better to have a check in the create method in the modelviewset class? Or in the models?

#

what is better when it comes to performance?
flask or django?

#

make sure your test modules/packages have valid python names

#

im getting this when running pytest

acoustic oyster
#

Flask is more lightweight in general, better for performance. But it also heavily dependns your programming.

native tide
#

the file name for testing is called test_back_end.py

#

can anyone help me out?

#

@acoustic oyster for dashboard for my discord bot, what will be better?

acoustic oyster
#

A small flask project will be generally "faster" than a small django project.

But if it is a very small project and it is for personal use, you will pretty much not see that performance difference.

If you want to use a database, django will be easier to set up imo

#

For reference: I was accidentlsly spamming api requests to my django site in a recursive loop earlier and I only noticed because of the logs. The site performance barely changed.

wind walrus
#

Are there any other free alternatives to amazon S3 to host static files?

#

Don’t think it matters but I’m using flask and deploying to Heroku with gunicorn

rigid laurel
#

S3 is pretty cheap. GCP also has storage buckets where you get some amount of stuff for free

wind walrus
#

Ohh I’ll look into Google Cloud thanks

#

Most blogs with just images won’t use that much storage anyway right?

#

So it’ll be like less than $1

#

On S3

flint breach
#

yea, s3 itself is dirt cheap

rigid laurel
#

s3 gives you 5gb of storage and a fair amount if ingress/egress for free - the only thing you might have to consider is actual malicious attacks, people spam requesting from it or something

rugged abyss
#

Hey guys, random question, if I use requests..post to send data to a server that I want to be modified, e.g. sending two numbers asking the server to multiply them, how do I get the response back?

rigid laurel
#

you need to set up a web server that will listen for the incoming request, process the request to do whatever, and then return the result

#

the specifics of that can be done in a million different ways

#

one way would be to set up a very simple Flask app

rugged abyss
#

Got it, any decent resource I can read to implement this?

flint breach
#

http rfc

#

👀

rigid laurel
#

It really depends on how much you need to do yourself and how much can be done for you

flint breach
#

for real though, perhaps to understand it, use something like flask to implement it, which is simple

rigid laurel
#

what is the actual task?

flint breach
#

writing an actual server and such isn't trivial, much less so if it's production grade

rigid laurel
#

Yeah, setting up Flask to be production grade is very annoying for this task

rugged abyss
#

I havent used python for web dev before so literally what I want to do is setup a server that I can ping with numbers and then it returns them multiplied

rigid laurel
#

for a quick+simple test, it's not too bad

#

Typically Python isn't the actual server though

rugged abyss
#

(based on this I will upload my ML algorithm which is more difficult but want to start here)

rigid laurel
#

that's what I'd start with

rugged abyss
#

I am using GCP for some more computing power so I dont have to load in my huge ml model on my compute

flint breach
#

well look into the sockets module, http refrence, and other computer networking resources if you're gonna do it from scratch

#

if you jsut want the functionality, look into flask like he said

rugged abyss
#

so its only for myself and doesnt need to be production grade

rigid laurel
#

Honestly, this task isn't that connected to the ML deployment stuff. If I were you, I'd just jump straight into trying to deploy the ML algorithm

rugged abyss
#

Okay, my end goal is essentially to use a VM on GCP where I will host my ML algo that I can then query

#

thought that was more or less analogous to the VM running a server that would respond to requests

rugged abyss
#

hence why I was doing it this way, but very open to do this another way

rigid laurel
#

I'd do that if I were you

flint breach
#

agreed, ^

modest scaffold
#

for some reason i changed my code a bit and the css file got loaded

#

could someone check my code to see if theres anything wrong i was doing

flint breach
#

post it

modest scaffold
#

k one sec

modest scaffold
#

this was my question the difference are in the question

flint breach
#

so it works now?

formal shell
#
def WorkFour(request, *args, **kwargs):
    form = CreateAdvertisement(request.POST, request.FILES)
    user = request.user
    teste =  user.ads.all()
    
    if len(teste) == 0:
        if form.is_valid():
            instance = Advertisement(**form.cleaned_data)
            instance.check()
            instance.user = request.user
            instance.save()
            return redirect('anuncio:w5')
    else:
        if form.is_valid():
            form.save()
            return redirect('anuncio:w5')
    context = {
        'form': form
    }
    return render(request, "trabalhe_4.html", context)

modest scaffold
#

@flint breach yup

formal shell
#

I'm trying to update this form in django, when It's used the else condition. It's not working, can anyone help me? Thanks in advance

wind walrus
#

In a flask app

#

If I want to add a multiple choice quiz to a blog post dynamically created on the website

#

Do I just do it with <script>? So I mix JavaScript code in my blog post?

brave glacier
#

hey im not sure if im asking in the right channel but i am very new to python and need some help. I am trying to print as shown in the image, provided with a list. im stuck on how to even print out the pattern, someone please help 😭

world_map = [['T', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\
             [' ', ' ', ' ', 'T', ' ', ' ', ' ', ' '],\
             [' ', ' ', ' ', ' ', ' ', 'T', ' ', ' '],\
             [' ', 'T', ' ', ' ', ' ', ' ', ' ', ' '],\
             [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\
             [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\
             [' ', ' ', ' ', ' ', 'T', ' ', ' ', ' '],\
             [' ', ' ', ' ', ' ', ' ', ' ', ' ', 'K']]
native tide
#

Anyone has experience with cPanel hosting ?

#

The client doesnt have terminal so i really dont know how should i handle the db changes. i can push migrations folder but how can i acheive anything without dropping the table eacch time something new is added

mental mango
#

Is it better just to use Django for everything or should I for example use Django for backend and reactJS for front end?

flint breach
#

I'm trying to update this form in django, when It's used the else condition. It's not working, can anyone help me? Thanks in advance
@formal shell is this used only for post?

formal shell
#

@formal shell is this used only for post?
@flint breach Yes, it is my friend

flint breach
#

the else looks valid

#

is it a model form?

#

also looks like the code could be cleaned, a bit, perhaps overwriting the form.save() to handle additional logic there

zealous siren
#

Spacecow react as front end is new hotness

#

Django as backend seems heavy

rocky lantern
#

Is the code jam is still running

#

If yes how can I take part

#

??

flint breach
#

it's not, you missed it

native tide
#

Hello, I am trying to use Flask to create a website, but I'm a little confused with main not being a resolved reference in the below code:

app = Flask(__main__)

#

It works when I replace "main" with "name" but then I'm unsure on what to do next because I'm not sure how to tell the app to run

formal shell
#

is it a model form?
@flint breach Yes, it is a model form, and this problem occurs when I click submit in the form (NOT NULL constraint failed: anuncio_advertisement.user_id).

flint breach
#

this is with the else?

distant trout
#

@merry geode

@distant trout It seems the image is base64 encoded. Just look up how to encode/decode base64 in Python

Thank you!

formal shell
#

this is with the else?
@flint breach Sorry for taking too long to answer, but yes. It's happening specifically because of the form.save()

rigid laurel
#

Are you checking the form is valid by calling .is_valid() first?
@formal shell

glass sandal
#

@native tide app.run()

#

And name is the name of file , main is the file that imports your current file

dapper falcon
#

This might be the wrong place to ask, but I'm creating a single page application with Flask. Is there a way to dynamically change the page content while keeping the url static?

glass sandal
#

You'll need to use AJAX

#

And there are some ways to change the url without the page reloading

native tide
#

Thanks rader

glass sandal
#

But sadly , since I'm not a frontend dev , idk

#

@native tide np

dapper falcon
#

Hmm, ok

#

Thanks

glass sandal
#

np

formal shell
#

Are you checking the form is valid by calling .is_valid() first?
@formal shell
@rigid laurel I forgot to pass an instace to my form.save(), now it is running ok.

#

Thanks for the help guys

#
@login_required()
def WorkFour(request, *args, **kwargs):
    form = CreateAdvertisement(request.POST, request.FILES)
    user = request.user
    form_update = CreateAdvertisement(request.POST, request.FILES,instance=Advertisement.objects.get(user=user))
    teste =  user.ads.all()
    
    if len(teste) == 0:
        if form.is_valid():
            instance = Advertisement(**form.cleaned_data)
            instance.check()
            instance.user = request.user
            instance.save()
            return redirect('anuncio:w5')
    else:
        if form_update.is_valid():
            form_update.save()
            return redirect('anuncio:w5')
    context = {
        'form': form
    }
    return render(request, "trabalhe_4.html", context)
#

That`s what I did

dapper raft
#

Hello i am thinking of starting web development with django how can I start what are the pre requisite of starting django

dapper tusk
#

have pip installed and scripts on PATH is the only one. django is on pypi

glass sandal
#

@dapper raft YT tutorials are good for beginners , documentation is nice too though!

#

@dapper raft Flask is better imo tho!

#

Like it's much much more flexible

#

It's lightweight

#

And you can just organize your code so much more

bleak bobcat
#

It depends on your needs

glass sandal
#

Well , you can make the same websites with both

bleak bobcat
#

Oh true. Just like you could make the same website going with bare python and 0 framework

dapper raft
#

I wnt to make simple blog

glass sandal
#

Then you can choose either of them

dapper raft
#

Where I can fetch data from an api

glass sandal
#

But if it were you I would choose flask

#

Using requests library

dapper raft
#

Request will block 😅 async Version is good right

#

aiohttp

dapper tusk
#

flask is not async, and django is only sort of async

dapper raft
#

Oooo

#

So django is the move?

#

Or flask

glass sandal
#

Based on your needs as @dapper tusk said

dapper tusk
#

if you want async, there is a flask like thing that is fully async afaik

dapper raft
#

Yes I wnt async

bleak bobcat
#

Go FastAPI then

#

Or starlette

glass sandal
#

I'd rather flask anyways . You can do everything Django does with it's libraries

#

But still

dapper raft
#

Actually I will use one module to fetch data from api

glass sandal
#

requests or urllib2?

#

I guess

dapper raft
glass sandal
#

Oh

dapper raft
#

It fetches data from game api

bleak bobcat
#

@glass sandal You're saying that just because you're much more familiar with Flask, that's not objective

glass sandal
#

@bleak bobcat I learned Django first

bleak bobcat
#

Doesn't mean you're more familiar with django

dapper raft
#

Well what market demands

glass sandal
#

But I've seen more websites for django tutorials than flask

bleak bobcat
#

He says he wants async and you answer with flask...

glass sandal
#

I am more comfortable with Django models too

#

But I use flask

#

And async could be done using third party libraries

bleak bobcat
#

Sure, you can use some async inside flask, but at the core it's still sync

dapper raft
#

Guys one more thing I wnt to take in consideration I wnt to learn framework which market wnts

glass sandal
#

If you want a job or freelance then Django

#

It has more jobs

dapper raft
#

Ok thanks buddies

bleak bobcat
#

Django is not async yet, it's comming but for now it barely has some async functionalities

dapper raft
#

Hmmmm your discussion helped me a lot

#

Ty for the info

#

🙂

glass sandal
#

@bleak bobcat So it's better using flask until that version thing comes

#

And @dapper raft np

bleak bobcat
#

Or FastAPI which is basically async flask...

glass sandal
#

Well , didn't know that framework

#

But he/she wants a framework that market wants too

bleak bobcat
#

Well market is not ready for async...

glass sandal
#

So he/she either has to choose Flask if async is so important or django if the market side is much more important

#

@bleak bobcat But he/she needs to learn a framework that he/she can use too!

shadow hornet
#

!ban 695267216102391868 joined just to tell people to die

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied ban to @hollow jay permanently.

glass sandal
#

I mean , Django is good too

#

But you know , when project gets big , you need flexiblity

bleak bobcat
#

Quite the opposite imo actually

#

When project gets big you need a structure everyone knows

glass sandal
#

That's for open source projects

bleak bobcat
#

Or company projects

glass sandal
#

a structure that you and your team understand is much better

bleak bobcat
#

There's nothing worse than working for a company for some time and leaving with only having learn their way of doing it

#

Will be applicable nowhere else

glass sandal
#

Well , for company projects just use Django . If I were to choose a framework for me and my team(If I had one) , then 100% flask , nothing else

#

Wait

#

lemme edit it

bleak bobcat
#

Again, depends on the project...Small project ? Sure, go flask

glass sandal
#

Flask is used in big projects too :/

bleak bobcat
#

It's small enough that everyone knows where everything is

glass sandal
#

Well , just use Django's structure

viral ocean
#

You don't have to have all your functionality come from one library

#

flask + other libraries can do everything django can

glass sandal
#

Yeah

bleak bobcat
#

That's not what we're talking about but ok

#

I already know that$

glass sandal
#

Well , just use Django's structure

bleak bobcat
#

So you're building django...on top of flask ? What's the point ? Wasting time ?

glass sandal
#

???? I said Django's structure

#

And you have much more flexiblity

#

Not a waste

viral ocean
#

Other functionality or better working functionality than is available in django

glass sandal
#

Yeah

viral ocean
#

django is great, but there are reasons people would want to use flask instead

glass sandal
#

When you use Django's structure , it doesn't mean you loose flexiblity

viral ocean
#

in a production enviroment

glass sandal
#

Yeah exactly

#

As I said , the market wants Django , despite all the cons . But as I said , you want to freelance or work in a company? Django . You have a team or you are going to develope a website yourself? Flask

native tide
#

In Django Rest Framework, how do I get the object from a url when I have HyperlinkedModelSerializers? Even the pk would be fine, but I don't seem to find a way that seems intuitive

flint breach
#

obj from an url?

mental mango
#

Flash and Django are both python web frameworks so surely learning one of them is going to make the other one easier.... Right?

#

So I can just learn Django then in the future if I want/need to I can pick up flask easier

flint breach
#

some concepts definitely apply so yea

#

routing, templates etc are all shared traits

#

as long as you pick up concepts, switching frameworks is a lot easier yea

fiery coral
#

Hey, good afternoon guys. I have a question. What should I know in Python before getting into Django? I really want to get into Django.

mental mango
#

Probably as much as possible tbh

fiery coral
#

Fair enough.

flint breach
#

django is a python framework, i imagine everything helps like he said

#

a lot of magic implementation details are hidden - metaclass magic to define how django objects (database objects) function

#

a lot of things like that, that you don't need to know, but if you do, it'll make you a better programmer overall

fiery coral
#

Alright, cool. I wouldn't say I'm a pro with Python by any means but I have been able to get basic things going with different libraries and I feel I have a decent understanding of it. Classes, objects, loops, vars, data types, stuff like that.

#

I'm going to go through the Django tutorial, it looks good.

late gale
#

Django is my favorite framework tbh

#

anyways

fiery coral
#

Are there any tough things with Django I should lookout for?

late gale
#

Nope , django is very easy and u wont do too much backend . most of stuffs django will handle it

#

i highly recommend watching Corey Schafer

fiery coral
#

That is awesome. Hey this guy has helped me learn a lot, he's got a lot major stuff. He helped me understand classes and objects, he explains really well. I will check this out.

late gale
#

Ofc Corey is someone very special. Glad you are excited 🙂

lucid vine
#

anyone have experience with creating an oauth2 client with python?

late gale
#

does anyone know how to make a button so when someone clicks on it it screenshot the current page and download it with the company's logo like this

#

as there is down the company name which is miro so i exported the page into an image

fiery coral
#

Question
urlpatterns = [
path('', views.index, name='index'),
]
How does this code work? I know it pulls the view index but how do I specify a URL to route to a different view?

#

urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]

#

And when the server gets polls/ it pulls up the index view

#

but how do I specify a different view to access if I wanted to add a new path like home/

dapper tusk
#

if you want wesite.com/home/ you want to add it to the project urls.py, if you want to have wesite.com/polls/home/ you put it in the polls app

#

include means all paths that match the pattern get routed to 'polls.urls'

fiery coral
#

Oh okay so would home be a different app?

quiet comet
#

im creating a ubuntu django server and my question is should i develop my project in the server or outside? it my firs time with a server, normally i just code localy

dapper tusk
#

I would suggest locally so that you get code reloading from runserver

#

if you want to have it as a separate app, make it a separate app, you could also make it point to a view directly @fiery coral

fiery coral
#

@quiet comet I think this helps you. This is from the Django tutorial.

Where should this code live?
If your background is in plain old PHP (with no use of modern frameworks), you’re probably used to putting code under the Web server’s document root (in a place such as /var/www). With Django, you don’t do that. It’s not a good idea to put any of this Python code within your Web server’s document root, because it risks the possibility that people may be able to view your code over the Web. That’s not good for security.

Put your code in some directory outside of the document root, such as /home/mycode.

#

how do I make it point to a view directly

#

@dapper tusk

dapper tusk
#

the same way you made it point to a view in an app pattern

native tide
#

@flint breach I have set up reverse relations already.

flint breach
#

Can you specify what you mean exactly then

native tide
#

So I have a user that is trying to subscribe to an event. The event is a foreign key attribute of the user. Then, when creating a user I want to check if the event is already full or not

#

Then, when getting the serializer data in the viewset perform_create method, I get a url for the event, because my EventSerializer is a HyperlinkedModelSerializer

#

but I want to get the event object, as I want to check 1) what is its capacity and 2) how many users are already attending

flint breach
#

Im gueesing hyperlinked is not the right serializer then

native tide
#

and the step I am missing is how to get the event object from the url that I get from the post data

#

I think there has to be a way

flint breach
#

I mean the point of the hyperlinked one is to for example show the links of all the related items in a gui or something not to get the ovjects themselves

quiet comet
#

my question was should i code in the server(which is a VM) or outside( my pc, windows), i think im going to code outside and after im done i will copy to the server so it will be deploy.

fiery coral
#

@quiet comet Yeah, I misread that.

flint breach
#

@native tide

#

Use a nested serializer is my suggestion

native tide
#

@flint breach interesting, I will look into that, thanks!

#

when i try to import a model from my models.py file

#

like this

#

from .models import Subscribe

#

i get no error

#

but when i try it from another file

#

i get this error

#

ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package

#

this is what i am doing

#
import smtplib, ssl, os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from .models import Subscribe

sender_email = os.environ['SENDER_EMAIL']
sender_password = os.environ['SENDER_PASSWORD']

recipients = []
for i in Subscribe.objects.all:
    recipients.append(i.email)
print(recipients)```
#

I am using Django btw.

flint breach
#

Is the file youre importig in, in the same directory?

native tide
#

yes

#
d-----        7/28/2020   2:15 PM                migrations
d-----        7/28/2020   8:43 PM                static
d-----        7/27/2020   6:26 PM                templates
-a----        7/28/2020   1:35 PM            125 admin.py
-a----        7/27/2020   6:23 PM             98 apps.py
-a----        7/28/2020   7:36 PM            253 forms.py
-a----        7/28/2020   2:15 PM            490 models.py
-a----        7/29/2020   4:09 PM           1431 send_data.py
-a----        7/27/2020   6:23 PM             63 tests.py
-a----        7/28/2020   5:48 PM            159 urls.py
-a----        7/28/2020   5:52 PM           1015 views.py
-a----        7/27/2020   6:23 PM              0 __init__.py```
#

why i use ls i get that

flint breach
#

Unfortunately my phone view of this is horrible

native tide
#

and in the send_data file i try to import models

#

ok. models.py and send_data.py are in the same dir

flint breach
#

Alright, can you specify fro@ which line the error is coming from

native tide
#
import smtplib, ssl, os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from .models import Subscribe # This line

sender_email = os.environ['SENDER_EMAIL']
sender_password = os.environ['SENDER_PASSWORD']

recipients = []
for i in Subscribe.objects.all:
    recipients.append(i.email)
print(recipients)```
#

@flint breach I am gonna for the nested serializer it fits exactly what I need, thanks! One last question, what is the better place to do the validation for whether the event is full, as a field validation on the serializer or as part of the perform_create method on the viewset class?

flint breach
#

Tbh wouldnt know till i see it, as long as it makes sense where it is, and stays DRY, you should be alright

#
import smtplib, ssl, os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from .models import Subscribe

sender_email = os.environ['SENDER_EMAIL']
sender_password = os.environ['SENDER_PASSWORD']

recipients = []
for i in Subscribe.objects.all:
    recipients.append(i.email)
print(recipients)```

@native tide what happens if you do an absolute import

#

Not sure whats causing the error

native tide
#

from .models import Subscribe causes the errorr

flint breach
#

Yea i know, does an absolute import cause the same error?

native tide
#

no

#

i did import subscribe.models

#

and got this error

#

ModuleNotFoundError: No module named 'subscribe'

flint breach
#

From subscribe import models?

native tide
#

if i do that

#

i get this error

#

ModuleNotFoundError: No module named 'subscribe'

#

👀

flint breach
#

You need to specify thr full path from the root of the project

native tide
#

@flint breach in the example from nested serializers from the docs (https://www.django-rest-framework.org/api-guide/relations/#nested-relationships) we have album and tracklist. When viewing the album details, we see the nested track objects info. However when viewing the track info, we would see only the album id. Is there any way that we can also see the nested album info in the track detail view without it being infinite nested? Maybe a second serializer class only for that purpose...?

cursive hound
#

Hey does anyone know how I should go about indexing a nested dictionary that is returned by a 3rd party API.

zealous siren
#

foreach your way through it?

cursive hound
#

I can do it that way but the data it returns needs to be saved in multiple spots. It’s returning a shipping label so I can’t run the method multiple times or it will create a few identical shipping labels.

zealous siren
#

you talking something like this: json { "index1": {"value2":"item1"} }

cursive hound
#

exactly

zealous siren
#

test to see if you already have the data

cursive hound
#

I have the data but it gets returned from a POST request

flint breach
#

You just use a different serializer in that case, with a reverse on the album, whichs serialized the data u need

zealous siren
#

Hamwallet, I'm too confused

cursive hound
#

'Response': {
'ResponseStatus': {
'Code': '1',
'Description': 'Success'
},
'Alert': [],
'AlertDetail': [],
'TransactionReference': {
'CustomerContext': 'Customer Context',
'TransactionIdentifier': None
}
},
'ShipmentResults': {
'Disclaimer': [],
'ShipmentCharges': {
'RateChart': None,
'BaseServiceCharge': None,
'TransportationCharges': {
'Code': None,
'Description': None,
'CurrencyCode': 'USD',
'MonetaryValue': '16.52',
'SubType': None
}

#

That is part of what is returned from the api

#

I only need to save a few specific portions of that data to a model but I can't run the POST request more than once

native tide
#

@flint breach problem is that then it interferes with the creation of tracks in that case, as the album field gets messed up for the POST request

#

I guess then you need to customize the creation method to use yet another serializer (for track in this case)

zealous siren
#

you have the data

#

response['response']['shipmentresults']['shipmentcharges']['RateChart']

cursive hound
#

yeah i just realized that, thank you

cursive hound
#

I tried that and now I am getting an error saying that list indices must be integers or slices, not strings

#

the data that is returned isn't a list however

acoustic oyster
#

something is a list haha

#

is response just a single response?

cursive hound
#

just figured it out, there was a list nested into the dictionary as a value

rustic pebble
#

Hi, so I had a critical incident in heroku, how can I see the logs for it?

#

I am able to see it through the metrics tab

cold anchor
#

what's the incident?

#

if you hover over it, what does it say

rustic pebble
#

A timeout

#

I wanna find the logs for it

#

It is probably caused by a bug I have been hunting for weeks

cold anchor
#

do you have a place you're sending logs?

rustic pebble
#

No, I don't. I don't usually use Heroku, client wanted :X

#

Do you have any idea on how I could store logs

#

and find out what that bug is

cold anchor
#

there are probably some logging addons for heroku you could add

rustic pebble
#

I use aws as well

cold anchor
#

AWS elasticsearch service has a free tier

rustic pebble
#

AWS do be the best

#

Heroku is not my preference, ever

cold anchor
#

yeah it's just an easier layer on top of AWS

#

so it's nice to get started or for small apps

rustic pebble
#

I usually use docker/k8s and an EC2 instance

cold anchor
#

k8s on GCP?

rustic pebble
#

EC2 is aws

#

yes

cold anchor
#

right, but kubernetes is not

rustic pebble
#

Kubernetes is supported

cold anchor
#

AWS ECS is the AWS version of it if you wanted them all in the same place

rustic pebble
#

by aws

cold anchor
#

oh nice

#

gotta look into that, I usually just do ECS

rustic pebble
#

It is actually rly nice

#

Basically, using anything other than Heroku was a dealbreaker for my client.

#

RIP

quick cargo
#

Is that just because they dont know of any other service tho lo;

rustic pebble
#

No damn idea

#

I asked them and they replied cause I like it more and I was like: you do you

rugged abyss
#

how would I deploy it to be available?

quick cargo
#

gunicorn is one of the most common methods

native tide
#

good evening everyone, in my django project I try to integrate sentry, but when launching travis it tells me ModuleNotFoundError: No module named 'raven'. however in my requirements.txt I have raven == 6.10.0. and I can't find a solution ... even on stackO

rugged abyss
#

any resources on how I would be doing that?

viral ocean
#

You can already access your website through localhost?

#

You just need to port forward then

acoustic oyster
#

can someone suggest the simplest way to maintain the aspect ration of an image in django? The built in ImageField apparently cannot read meta data, so all images become landscapes upon uploading.

proper hinge
#

You'll need to get the metadata somehow, so I suppose that means a third party library

acoustic oyster
#

ok, that is what I am seeing. I see django has height_field() and width_field() But it is unclear to me how to use these

proper hinge
#

You're talking about EXIF orientation, right?

#

If so, I wonder if you can subclass the field and create one that supports loading EXIF metadata with a library

#

And you could use some CSS to transform the image based on orientation if you plan to display it.

#

Assuming you want to preserve the image as is. The other option is to just rotate the image and re-save it

acoustic oyster
#

I am using a JS library that uses the aspect ratio to display the images.

#

I mean, the lazy way is to add an option for portrait or landscape LOL,

#

I'm just surprised this is not built into django, it seems like a common task

#

and yes

#

I need to tell my js if it should be displayed in portrait or landscape mode, but django makes all images landscape 😢

#

ill make my user explicitly say if it is portrait or landscape pats self on back

proper hinge
#

I'm still not sure if you're talking about EXIF orientation or not

acoustic oyster
#

well, the issue is any image that is taller than it is wide is perceived as landscape as well as any image that is wider than it is tall.

This is for uploading art, but the result is stretched images that do not fit.

#

I am unsure where exif applies, but I assume yes

proper hinge
#

Okay, that doesn't sound related to EXIF.

#

I feel like this is just a CSS thing

acoustic oyster
#

well, my app uses the django api to get the image urls and the aspect ratio. But the width is always the largest number and y is always the smallest number.

I need the user to be able to upload an image, save the original x and y dimensions, then include those x, y dimensions in the api with the url so that the React app can load them in

#

the issue is that the default dimensions are always width == max(width, height), height == min(width, height

#

for all image files, both pictures from android and iphone and also drawings in png, jpg format from photoshop or other drawing related apps.

#

I am finding very few similar issues online

proper hinge
#

Is it only the dimension attributes that are wrong, or is the image itself modified too?

#

Like, if you open the URL in your browser, does the image look fine?

acoustic oyster
#

sorry, SOME images are fine, some break.

one sec, lemme test that

#

hmm, well. It is hard to test. It appears maybe a group of images I was using is somehow corrupted (?) most drawn images work fine, no pictures work

proper hinge
#

Well... maybe it is EXIF after all if it's failing on photos

#

Cameras add metadata in the form of EXIF to photos.

acoustic oyster
#

ty, I learned a lot today about file formats haha

proper hinge
#

The image is stored one way but the EXIF orientation metadata tells image viewers to display it some other way

acoustic oyster
#

I do not think the user will plan on ever uploading pictures here. But I dont feel right ignoring it.

I am mostly surprised this is not built into django

proper hinge
#

If it's an EXIF thing then I'm not surprised.

#

You should find those problematic images and check if they have an orientation in the exif tag

#

Pillow/Django is likely just reporting how the image is actually stored rather than how it wants to be oriented

#

If it's not an EXIF issue then I don't know what it could be

acoustic oyster
#

it is probably EXIF and like a small handful of problematic images, but they are all from the same batch of downloads, so maybe there was an issue there

tawdry elbow
#

Hello! I'm working on a vulnerable Flask app for a training site and it's my first time going this in depth with the Framework. I have a Products page that has my fictional products and a button to find out more about the specific product. I want the button to trigger a new page as well as create a sql query on the backend to return back to a new page of /products/product

#

I'm stuck on how to do this

balmy shard
#

Bois i need some help with flask

#

Are there any hosting services that support flask

#

Or could I host it myself

#

@ or dm me if anyone knows

native tide
balmy shard
#

Thank you

native tide
#

yee

tawdry elbow
#

I need some help with my issue still as well if anyone is free

sturdy pike
#

Depends on the issue @tawdry elbow

#

Oh i see up there.

tawdry elbow
#

I'm planning a purposely vulnerable Flask server. The idea is for the user to go from /products and click on the Learn More buttons to go to the specific /product page for that product. That page will call the SQL server and make a vulnerable SQL query

#

But im having trouble figuring out the best way to creating this route from /products to /product

#

Currently I just have ```py
@app.route('/products', methods=['GET'])
def products():
return render_template('products.html', title='Our Products')

#

Which renders this

sturdy pike
#

That's pretty legit

tawdry elbow
#

Thank you sir

sturdy pike
#

Unfortunately I have no flask knowledge. I'm a django girl

tawdry elbow
#

maam

sturdy pike
#

lmfao

tawdry elbow
#

insert gender neutral pronoun

#

's all good

#

I should be studying for sec+ anyway

sturdy pike
#

I'm sure someone will come along. Yeah same. K do ur thing

fiery coral
#

hey

#

Issue with flask

#

app = Flask(main)

#

tells me main is not defined

fiery coral
#

figured it out

quartz valley
#

@fiery coral main isn't valid. You need to use __name__.

fiery coral
#

@quartz valley Yeah, I was following a tutorial and they messed up. Thanks.

tawdry elbow
#

I was pinged?

#

@quartz valley I think it was you

quartz valley
#

@tawdry elbow I started typing without actually explaining my thoughts well

#

Ignore me

#

Sorry

soft chasm
#

Hey has anyone come across a nice plotly venn diagram example? For some reason there seems to only be kind of a lame static one, i was hoping for a nice dynamic web one i could put into a Dash app.

#

(with mouseovers of each of the sections to show number of elements etc)

bleak bobcat
harsh trench
#

Hello

#

i am using flask i am getting some error

soft chasm
#

@bleak bobcat Nice, ta!

harsh trench
#

Lol fixed

tawdry elbow
#

I'm still having some issues with my flask app. They are described abobe

#

Above

#

If anyone needs more info let me know

#

Maybe that's why no one has helped lol

manic frost
#

Is it possible to make an ASGI server work on a platform that only supports WSGI? Is there some sort of adapter?

#

I'm building an app using FastAPI, but it's going to be hosted somewhere where ASGI isn't supported (I think)

quick cargo
#

Asgi should be supported by anything in theory

#

Asgi is just the async implementation over the sync version WSGI

#

It would fairly simple to turn as ASGI -> WSGI but not the other way round really, because the environ dictionaries and callbacks differ alot

modest scaffold
#

where does django looks for a media folder in an app

#

because it can't find my media folder

#

for some reason it can find my static file but not the media folder

quick cargo
#

@manic frost Whats the host? and type?

manic frost
#

Um, well, I haven't decided yet. My hosting, and probably other hostings in that price range use an Apache server and through some magic (with passenger) run a WSGI app.

quick cargo
#

hmmm

#

You are probably going to be limited i think

manic frost
quick cargo
#

Some WSGI runners use things like PyUv to have essentially sync based event loops where they can fight each other

manic frost
#

well, if I fail, I could use heroku, right?

quick cargo
#

Whats your budget?

#

something like linode or Contabo do some really cheap hosting that gives you VPS control

manic frost
#

my budget is epsilon because it's for personal stuff for now

quick cargo
#

ah fair enouh

#

enough*

#

You can try that ASGItowsgi adapter but it might have some unintended concequences

#

couldnt hurt to try tho

manic frost
#

the hosting is pretty crappy... it shadows 500 errors with non-descriptive 503 errors haha

#

but I was content until I started using FastAPI

stone wren
#

how can I customize model.query return?

for example my UserModel has packages which is foreign key to PackageModel

when I query UserModel.objects.filter(whatever) I want my packages to return all except delivered packages -- (current_state != 'Delivered')

#

these are my models

class UserModel(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, Sequence(
        'user_id_seq', start=10001, increment=1), primary_key=True)
    
    is_admin = db.Column(db.Boolean, default=False)
    is_superuser = db.Column(db.Boolean, default=False)
    packages = db.relationship('PackageModel')


class PackageModel(db.Model):
    __tablename__ = 'package'
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey(
        'user.id', ondelete='CASCADE'), nullable=False)
  
    current_state = db.Column(
        db.Enum(PackageState), nullable=False, default=PackageState.Declarations)
    user = db.relationship('UserModel', back_populates='packages')
cold anchor
#

it's best practice to make that a model method

#

class PackageModel(db.Model):
    ...

    @classmethod
    def not_delivered_for_user(cls, user_id):
        return cls.query.filter(cls.user_id == user_id, cls.current_state != 'Delivered')
#

and that returns a query and you can do whatever query methods you want (another filter, get the .first(), get .all() results, etc.)

grand dew
#

hello everyone. having some trouble with flask

#

I have configured a 404 page

#

(my 500 page doesn't work and I'd also like to tackle that)

#

but it doesn't get triggered too often

#

and at this point, I intentionally want my website to trigger loads of 404 pages. how do I sensibly make that happen?

#

because my 404 gets triggered under very specific situations -- but not all

flint breach
#

404, is when you enter a url that's not defined in your routes, that's when you return the 404 page

#

localhost:8000/lalala

grand dew
#

lol -- creepy stuff. I literally test with /lalala lol

#

but how do I point flask to that? if I do localhost:8000/lalala I get 500

#
@app.route("/oops/")
def oops():
    return not_found()

@app.errorhandler(404)
def not_found():
    return render_template("not_found.html", data=today_date, page="erro"), 404 ```
#

I managed a workaround by defining links that are meant to route to 400 to go to /oops/, which renders the 404 page

#

is there any way to make /lala route to 404? I can make it with lousy if conditions, but I'd rather use a flask tool if there is one

flint breach
#

in django, a middleware automatically redirects the user to the 404 page, not familiar with flask so can't tell you directly, but surely there must be some option to do the same

grand dew
#

Ooooh! I just fixed it!

#
@app.errorhandler(404)
def not_found(e):
    return render_template("not_found.html", data=today_date, page="erro"), 404 ```
#

this fixes it -- e as the argument for not_found

#

cool. thank you for the help!

flint breach
#

im glad you fixed it 🙂

late fjord
#

I am trying to make a decorator that return a user to a certain url when he tries to go the register page and he is logged in

def unauthenticated_user(view_func,redirect_url):
    def my_func(request, *args, **kwargs):
        if request.user.is_authenticated():
            return redirect(redirect_url)
        else:
            return view_func(request, *args, **kwargs)
    return my_func```
please help me
#

when I try to call it in my view func it tells missing one required positional argument view_func

#

@flint breach can you help

#

this is the code in my views.py :

@unauthenticated_user(redirect_url='/user/register/')
def register(request):
    form = CreateUser
    if request.method=="POST":
        form = CreateUser(request.POST)
        if form.is_valid():
            user = form.save()
            if user is not None:
                login(request, user)
                return redirect('/posts/')
            else:
                messages.error(request, 'Password or Username is incorrect')
    return render(request, 'users/register.html', {'form':form,})



flint breach
#

which positional arg are you missing

late fjord
#

the view_func

flint breach
#

that's not a positional arg, just paste the error msg

late fjord
#
TypeError: unauthenticated_user() missing 1 required positional argument: 'view_func'

dapper tusk
#

the way decorators with parameters work is like so

@decorator(arg)
def fun(args):
  pass

is the same as

def fun(args):
    ...
decorator_to_apply = decorator(arg)
fun = decorator_to_apply(fun)
late fjord
#

I didn't get it @dapper tusk

dapper tusk
#
unauthenticated_user(redirect_url='/user/register/')
``` has to return a function that takes the view func
#

so you would write it like so

def unauthenticated_user(redirect_url):
    def decorator(view_func):
        def my_func(request, *args, **kwargs):
            if request.user.is_authenticated():
                return redirect(redirect_url)
            else:
                return view_func(request, *args, **kwargs)
        return my_func
    return decorator
late fjord
#

thank you so much @dapper tusk

native tide
#

if i am in my app folder in Django

#

how to i get a function from the views.py file

#

example:

#

my view file looks like this:```python
from django.shortcuts import render, redirect, reverse
from django.http import HttpResponseRedirect
from .forms import SubscribeForm
from .models import Subscribe

def foo(i):
return i

Create your views here.

def home(request):
context = {'text': 'Thanks for Subbing'}
return render(request, 'subscribe/home.html', context)

#

and i want to import the foo function from another file

flint breach
#

like you'd import a function from any other file

native tide
#

this file

#
from apscheduler.schedulers.blocking import BlockingScheduler
from .views import foo

sched = BlockingScheduler()

# Schedule job_function to be called every two hours
sched.add_job(foo, 'interval', seconds=30)

sched.start()```
#

yes

#

the file above is called send_every.py

#

send_every and views.py are in the same dir

#

but this line from .views import foo gives me this error ModuleNotFoundError: No module named '__main__.views'; '__main__' is not a package

#

I had this problem yesterday too @flint breach if you remember

#

i'm stuck here

#

I have tried from views import foo and from subscribe.views import foo

#

those don't work

flint breach
#

Same error?

#

also, got an __init__ in the folder?

#

it has to be a package (a package has a __init__.py file) for relative imports to work

#

your project structure would help greatly

#
❯ tree
.
├── app1
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── app2
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── app3
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── demo_project
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── manage.py

7 directories, 26 files
#

if you want to, for example, import app2/views into app2/tests, then from .views import something should work

tawdry elbow
#

With Flask, I have my models.py file to be used with SQLAlchemy. Do I need to manually create the tables in the Database with the right rows or will I do that in the app?

#

Everything in my app is going to be predefined and set already. I'm not creating records in the DB through like a user registration. Do I need models.py at all?

flint breach
#

sounds to me like you're describing a static site

#

if you have no db interaction, you don't really need it then, no

tawdry elbow
#

I do

#

There is DB interaction

#

I'm querying it to return fields from it

#

But I'm not making entries into it at all

flint breach
#

never?

#

and if never, how much data do you have

tawdry elbow
#

Only 4 things for products

flint breach
#

if the answer is never, and little, a db seems overkill to say the least

tawdry elbow
#

Maybe so but it has a purpose here

#

I'm designing it to be intentionally vulnerable to SQLi

flint breach
#

sqlite?

tawdry elbow
#

MySQL

#

Goin for realism where possible

#

Also on purpose

flint breach
#

wew, seems very overkill

tawdry elbow
#

Yes probably

#

Do I even need SQLAlchemy?

#

Or can I use Flask-MySql

flint breach
#

sqlalchemy sounds overkill, a full blown orm

#

but then again, so does mysql, so 🤷‍♂️

tawdry elbow
#

So how can I do this

#

Just cuz it's overkill doesn't mean it isn't possible

#

I just need some help

#

Would Flask-MySql be better suited?

#

Then I don't think Id need SQLAlchemy

flint breach
#

don't get me wrong, of course it's possible, im just not familiar with flask, so im waiting for someone else to give better advice 😛

tawdry elbow
#

Ah okay haha

#

So far I keep getting skipped over so I might be on my own

brave elbow
#

I am making a web app using flask. in my app.py file, I am trying to import modules from a custom module file that is in the same directory. my editor (vscode) is saying "unresolved import".

hallow jacinth
#

make sure you are in the same working directory, that was my issue when I was trying to use custom modules

brave elbow
#

sorry, im not sure what you mean. both the app.py and my module.py file are in the same dir. also in the dir is my templates dir and static dir

hallow jacinth
#

claim a help channel and ill see if I can help you fix it :D

brave elbow
#

im in hydrogen

#

thank you

distant trout
#

can someone tell me why does postgres have 2 id columns? using flask sqlalachemy? the first ID column works normally but the 2nd id columns increments and stays even after one is deleted.

example:

user one = ID #1
I deleted user one.
i create user one again = ID #2

dapper tusk
#

Sqlalchemy probably automatically create a primary key as an auto increment id

#

The IDs are not reused because they are often used as unique identifiers

distant trout
#

ahh, that makes sense! thank you!

native tide
#

Does anyone know of any professional websites that are coded with Python Django?

cold anchor
#

instagram & pinterest

native tide
#

Are they coded fully in Python Django?

cold anchor
#

I'm sure there are some aspects that are outside django, such as the frontend and mobile apps, product analytics, etc.

cold socket
#

If I have images in a random directory on a remote server, can Flask somehow connect to it and display the images on the frontend (Flask would be running on a separate server)

#

Can this be done without using a database

tawdry elbow
#

If I'm adding all of the entries to my tables through the MySQL shell and only need to perform queries on the database (SELECT only), do I need an ORM?

#

Can I just use Flask-MySql

cold socket
#

I'd go with SQLAlchemy

tawdry elbow
#

Full disclosure my tables aren't going to ever be modified by the app or be added to. They're just there to be queried

#

I need the app to be able to make raw SQL queries too. I haven't seen how to do that with SQLAlchemy

#

I already have my models and all with SQLAlchemy but I just don't know how to configure it for MySQL. I only ever see sqlite tutorials

#

And guides

#

What do you think? @cold socket

cold socket
#

@tawdry elbow Do you mean something like rs = con.execute('SELECT * FROM table;')

tawdry elbow
#

Mhm

cold socket
tawdry elbow
#

That helps a bit

lofty matrix
#

With REST endpoints, what is the best practice for this scenario?

I want the client to initiate the creation of an object on the server, but the client isn't specifying any details about the object being created; that is all being handled by the server.

Is it ok to POST to /my_objects/ with no data, or is there a more preferred way?

left jungle
#

Hi, I have a important question. How can i deploy flask app to apache? Is it possible to run apache on raspberry pi (zero)? I haven't find helpful tutorials so I am asking here

bitter patrol
#

Open your own help channel pls

glass sandal
#

Guys is it possible to deploy a flask application to an apache server? If yes , how?

#

And mention me if you want to answer please

modest scaffold
#

why cant django find my media filelelele can someone please double check im doing this media file things right

balmy shard
#

bois i have a question about gunicorn

#

how do i make it run outside of localhost?
pls @ or dm me if you have an answer

native tide
#

Anyone knows why is uvicorn called uvicorn?

eager mural
#

@left jungle flask and apache are very different, generally you don't mix gjr two

wanton ridge
#

Anyone know how to save datas from website directly to database....i also have a submit button after i click in it i wanna save those data to the database....i have a webserver python and a post method in <form> too and i wanna save those datas in website in database after i started my webserver and click on submit

acoustic oyster
#

@left jungle I host my Django with apache. I am sure Flask would work as well, but I do not use flask.

Yes, you should be able to run flask on Raspbian (I think they renamed it)

#

@wanton ridge are you using a framework? With Django this would be handled most likely through an API call or simply through the view by running the .save() method on your form

cerulean eagle
#

somebody know ho to write a proxy for nike login ?

stone wren
#

it's best practice to make that a model method
@cold anchor I know, but, there is a reason.

right now, I really need to make PackageModel return that way. how do I change model return default?

wanton ridge
#

anyone familiar with http server?

bleak bobcat
#

Nah, nobody is. What's the question ?

wanton ridge
#

get data directly to database with http server

bleak bobcat
#

What's the action on your form ?

junior river
#

if anyone can help me with a bot I'm making to pull jpegs off a website and tweet them, i would appreciate it very much...I started this project in JS, but I think I should probably be using python.

#

I have a twitter dev account made already and have it set up to be able to tweet stuff...but I might as well be doing it manually if I can automate the image scraping to use to tweet

wanton ridge
bleak bobcat
#

Well that's not how it works...The action needs to be a url

wanton ridge
#

i also try it

#

but after click on button datas wont be send directly to database

#

i also connect my python to mariadb

bleak bobcat
#

Because you need to process it and send it to the database yourself, it's not magic

acoustic oyster
#

your code writes a hard-coded commit to the database, you need to write a way to parse your data that is passed to do_POST()

wanton ridge
#

cant u just click on submit and those datas will be send directly to database?

#

let me send code

acoustic oyster
#

no

bleak bobcat
#

No

acoustic oyster
#

you can send your data to your SERVER, the database needs to know what it means

wanton ridge
acoustic oyster
#

This is similar to:

If you throw peanuts and grapes at a loaf of bread, it does not make a peanut butter and jelly sandwich.

You first need to make peanut butter from the peanuts, jelly from the grapes. You STILL dont have a sandwich, so now you need to assemble everything

wanton ridge
#

and my values are %s and after it succes record i search the SELECT * form antworten11 i get those %s

#

This is similar to:

If you throw peanuts and grapes at a loaf of bread, it does not make a peanut butter and jelly sandwich.

You first need to make peanut butter from the peanuts, jelly from the grapes. You STILL dont have a sandwich, so now you need to assemble everything
@acoustic oyster lol yh

acoustic oyster
#

You get data from the form => data goes to JS => data goes to python => you then clean and parse the data => you send the data to SQL with a query

wanton ridge
#

yep after click submit i can go to inspector and see those datas as json which i made in js

#

but then i have to type those manually in insert into antworten11 VALUES... myself but i dont want to type it manually

iron cliff
#

I want to redirect to login page after logging out from the administration page too. How can I do that? (django 3.x)

cerulean eagle
#

can somebody please show me how to code a nike login..

rich thunder
#

hello

native tide
#

What is the best database to use for implementing a login system on a website?

rich thunder
#

I am beginner in django and I need a simple help

bleak bobcat
#

Did you try to run urls.py ? oO

#

Run manage.py runserver

tawdry elbow
#

https://hastebin.com/vomibupoho.py Can anyone help me and tell me if I'm making the connection and performing the SQL the right way? I know you aren't supposed to make a new connection per request so I'd want to do it the right way. Does anybody have any tips?

#

I need to use raw SQL so that's not my issue

upbeat forge
#

Sup beautiful people, i was trying to connect mysql to django but apparently while installing mysqlclient it shows an error.

#

It says the wheel is not supported on this platform

#

I was trying to do it on windows before, havent tried it on linux.

merry geode
#

https://hastebin.com/vomibupoho.py Can anyone help me and tell me if I'm making the connection and performing the SQL the right way? I know you aren't supposed to make a new connection per request so I'd want to do it the right way. Does anybody have any tips?
@tawdry elbow You're not supposed to use f-string or any kind of string concatenation while passing user input values.
Db libraries provide parameterization for Db queries, like so:
cur.execute("select * from table where col = %s", ("value",))

tawdry elbow
#

Okay good I'm glad you caught that

#

It's done on purpose

#

Any other suggestions on changing how the database is connected to? I would think I'd want to open a connection upon the app being loaded (i.e. the main index being requested) and then pass that connection around to my other routes to make queries on...or rather, just the one lol

#

How would I do that?

flint breach
#

real talk

#

why does related_name='+' in django exist

#

just an annoyance that the reverse relationship is not available

balmy shard
#

bois

#

i need some help

tawdry elbow
#

Me too

balmy shard
#
        content = post [1] + ': ' + post[2]```
should display things in a list like this 
```name: content
name1: content1```
#

but it displays this instead
[(message id, 'name', 'content')]

#

if anyone has any ideas

#

pls @ me

flint breach
#

how is this relevant to webdev?

stone girder
#

how do u set a background image on flask?

tawdry elbow
#

You mean in CSS?

stone girder
#

ya in css

#

but i got it nvm

balmy shard
#

how is this relevant to webdev?
@flint breach because its getting the input/input variable from flask and outputting it to another flask site

flint breach
#

fair, but the specific code section that's bothering you has nothing to do with webdev, more of a general py question

#

can you show the posts variable

limber laurel
#

How do you display the content?

balmy shard
#

can you show the posts variable
@flint breach
posts is
posts = get_posts()
and thats a function from another python file i imported

    con = sql.connect(path.join(root, 'database.db'))
    cur = con.cursor()
    cur.execute('select * from posts')
    posts = cur.fetchall()
    return posts```
native tide
#

anyone know which SQL engine has the least issues with Django? Tried installing MySQL and it just gives a bunch of wheels issues, even tried downloading the mirror someone suggested on Stack Overflow and still the same issue, smh.

flint breach
#

Sqlite is the simplest

native tide
#

sqlite for a production app though?

flint breach
#

nah, i'd recommend postgres

native tide
#

ok

flint breach
#

mysql or mariadb shouldn't be problematic either afaik

native tide
#

any specific version of postgres

flint breach
#

meh, anything that's not bleeding edge (the latest version) or an old ass version should be fine

native tide
#

ii

tawdry elbow
#

Can anyone help me with my question? I'm trying to figure out the best way to create my connection to my database so it doesn't break anything or cause unnecessary lpad

#

I'm not sure what I'm doing currently is correct

balmy shard
#

Can anyone help me with my question? I'm trying to figure out the best way to create my connection to my database so it doesn't break anything or cause unnecessary lpad
@tawdry elbow what kind?
i mean whatre you using to connect to it (sqlite, postgres, etc)

flint breach
#

@flint breach
posts is
posts = get_posts()
and thats a function from another python file i imported

    con = sql.connect(path.join(root, 'database.db'))
    cur = con.cursor()
    cur.execute('select * from posts')
    posts = cur.fetchall()
    return posts```

@balmy shard print(posts) for me

balmy shard
#

@balmy shard print(posts) for me
@flint breach [(330, 'Cylinder', 'test')]

flint breach
#

and you want the list to be ['Cylinder: test'] or what?

tawdry elbow
balmy shard
#

id like it to be

Other_name: test
flint breach
#

where do you get other_name from

balmy shard
#

i just made up the other one

flint breach
#

you just want to print it or have a new list from it?

#

or, modify the existing list?

balmy shard
#

i think put it in a variable

#

printing it would be kinda useless

scenic dove
#

Hi, for DRF, is it okay if I only have JWT Authentication under DEFAULT_AUTHENTICATION_CLASSES or will I not work with sessions?

The problem I'm facing right now with sessions enabled is whenever the server restarts, it deletes all sessions and it doesn't seem to check if there's an existing JWT token so it just throws an Unauthorized error.

flint breach
#

perhaps a dict

balmy shard
#

ok

flint breach
#
new_posts = {key: value for _, key, value in posts}```
#

that's one option, given that you don't really know what you want with it 😛

balmy shard
#

thank you

#

i might make it email or save it

flint breach
#

one tip, think what you wanna do with it, before you start coding

#

otherwise you'll just stumble over yourself

#

i don't think you gained much by having it in a dictionary, unless you need constant lookup time

#

but im gueesing you don't really?

balmy shard
#

i dont rly know what the plan is for any of this

#

its more of a time killer

flint breach
#

fair

balmy shard
#

i don't think you gained much by having it in a dictionary, unless you need constant lookup time
@flint breach i made a thing to send it to a mailtrap inbox so i can keep it without looking at the database or turning on the site

limber laurel
#

What are th differences between one database and another

rigid laurel
#

Acid

balmy shard
#

coffee

cloud path
#

guys where can i learn to set up a web server after learning to develop a website through flask?

atomic zinc
#

Hello all. I hope you have a great day. I feel confident with the basics of Python and now I want to start my journey with web development. Any recommendations from where to start?

cloud path
elfin tinsel
#
@app.route('/logout', methods=['GET'])
@client.is_logged_in
def logout():
    client.logout()
    return redirect(url_for('index'))

I have a route like this, and I provide a redirect too. Still it returns an error

Traceback (most recent call last):
  File "C:\Users\kanna\.virtualenvs\OpenCity-Dashboard-9CrIeGsV\lib\site-packages\flask\app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\kanna\.virtualenvs\OpenCity-Dashboard-9CrIeGsV\lib\site-packages\flask\app.py", line 1953, in full_dispatch_request
    return self.finalize_request(rv)
  File "C:\Users\kanna\.virtualenvs\OpenCity-Dashboard-9CrIeGsV\lib\site-packages\flask\app.py", line 1968, in finalize_request
    response = self.make_response(rv)
  File "C:\Users\kanna\.virtualenvs\OpenCity-Dashboard-9CrIeGsV\lib\site-packages\flask\app.py", line 2097, in make_response
    raise TypeError(
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
atomic zinc
#

@cloud path thank you

native tide
#

how worth it is it to learn django? im just getting into it and it seems like it handles sessions & saving them to the db which is awesome

distant trout
#

django probably worth learning, but as a beginner i chose flask and id say i made the good choice

#

i watched some django tutorials and it seems easier cuz the concepts feel the same to me

fossil bay
#

Has anyone here worked with flask? I'm having trouble getting AJAX to successfully send a JSON to my flask script.

rigid laurel
#

Sure. Can you post an example of both the js and the flask

fossil bay
#

Sure thing!

#

I think that's the link. I put them both on the same document here, but they are in seperate files obviously haha.

#

That's just the flask route for the specific page. If you need the rest of the flask, let me know!

rigid laurel
#

I don't remember the Jquery side of things well enough to say exactly what's going wrong - but I'm pretty sure the problem is on that side of things

fossil bay
#

That's what I figured. I'm terrible with JS and Jquery haha

rigid laurel
#

I'm assuming this never triggers? print(test)

fossil bay
#

Correct, it times out with get.

#

For some reason it's sending testVariable as a nonetype

rigid laurel
#
    document.getElementById('submit_button').addEventListener('click', function () {
      var testVariable = "hello, this is a test";
    $.post( "/", { name: "John", time: "2pm" } );
  })
#

try replacing you js with that

#

json.stringify is converting a javascript object into json format

#

but you want to be sending it a object I think

fossil bay
#

Still considered nonetype