#web-development

2 messages · Page 226 of 1

serene prawn
#

You're creating new model, not getting one from db

hard whale
#

Maybe you can show an example of how to do it properly?

#

no idea why it's not on fastapi docs

serene prawn
hard whale
#

thanks, i'll try that! and for update?

serene prawn
#

Hm, actually it's better to use scalar or just raw delete statement here, HTTP Delete should be idempotent

hard whale
#

i couldn't find method for it

nimble berry
#

not exactly, and we use asymmetric encryption on the client side with replay protection to encrypt the passwords with a public key before sending them to the service

serene prawn
#
stmt = delete(Item).where(Item.id == some_id)
await session.execute(stmt)
await session.commit()
serene prawn
nimble berry
#

@serene prawn so anything in-between would be blind to the password

serene prawn
#

Also in case of mitm attack won't attacker be able to substitute his own public key?

nimble berry
# serene prawn Also in case of mitm attack won't attacker be able to substitute his own public ...

i don't have all the details in my head right now
but if someone where to compromise the infrastructure as such that the would be able to control the content that is received by our clients when they visit the site no amount of encryption would help
at the very least one has to compromise different parts of the infrastructure to do something like that since the static content including the javascript and the public key of the SPA comes from a different places then the services that receive them, and then there is tls on top of all that
for the mobile apps it's already a part of the client application that is signed and distributed through apples app store and google play

serene prawn
nimble berry
serene prawn
#

You're trying to mitigate mitm attacks by encrypting the password, which you're still vulnerable to (at least it seems like to me)

nimble berry
# serene prawn I think in this case encrypting password at client side doesn't really make sens...

depends, it's an added layer of security that helps in some situations but not others, if the client is fully compromised not much will help
it's not just username and password as we are using different forms of MFA as well and are trying to move away from passwords all together, but it can be hard to retire passwords with a big user base that can be quite ridged to change and not all customers are technical enough, so we do the best we can 🤷‍♂️

nimble berry
hard whale
#

@serene prawn ```
device_delete = delete(device).where(device.id == location)
NameError: name 'delete' is not defined

#

I got this 😦

#
@app.delete("/device/del/{location}", response_model=DeviceRequest)
async def delete_device(location: str, db: Session = Depends(get_db)):
    device = Device()
    device_delete = delete(device).where(device.id == location)

    db.execute(device_delete)
    db.commit()
serene prawn
#

and device_delete = delete(Device).where(device.id == location)

#

Device, not device

hard whale
#

Does it matter if i mention device = Device()

#

?

serene prawn
#

You don't need to create new model here

#

remove that line

hard whale
#

ok

#
@app.delete("/device/del/{location}")
async def delete_device(location: str, db: Session = Depends(get_db)):
    device_delete = delete(Device).where(Device.id == location)

    db.execute(device_delete)
    db.commit()


    return {
        "code": "success",
        "message": "device deleted"
    }
#

This looks correct?

serene prawn
#

Yep

#

You can change url to /device/{location}

hard whale
#

Strange.. Doesn't delete anything

serene prawn
#

change Device.id to Device.location?

hard whale
#

I have GET for /device/{location}, won't they conflict?

serene prawn
#

Nope

#

They use different methods

hard whale
serene prawn
#

Rest recommends using uri's to identify specific objecst, e.g.
/items/{itemId}

#

And you can use different verbs to get, update, patch and delete it

hard whale
#

Nice, thank you for all the info and help, now it works!

#

PUT/update left and i'm done for today

#

I wish I started this project with SQLModel)

serene prawn
hard whale
#

any benefits?

#

i just like the docs for fastapi and sqlmodel, very newbie friendly

#

good examples are the best way to learn

serene prawn
#

also sqlalchemy docs have a lot of examples for different use cases

hard whale
#

Yeah, now they don't seem so useless to me, they just need some background for understanding

#

BTW as long as I have all I need on my server part could you share some ideas regarding client? Server will return json message to client device, what would I need on client side to receive json after sending request to server API and and to drag variables from it?

#

I mean which modules/libs i should use

serene prawn
#

Depends on what your client is

#

@hard whale

hard whale
#

@serene prawn just a python script that will knock on the server to let him know he is online and his main goal is to receive some variables from server to do some calculations and return back to server after

serene prawn
hard whale
#

@serene prawn

#
import json,urllib.request
data = urllib.request.urlopen("url").read()
output = json.loads(data)
print (output)
#

somewhat like this?

zealous sorrel
#

Hello, I am using xhtml2pdf to convert my template into html but bootstrap doesn't seem to work, any ideas?

golden hamlet
#

yo bois, should i first do flask and then django?

#

i'm done with python basics so i wanna move on to web-dev

uncut lark
rigid laurel
golden hamlet
#

thing is.. i don't have a clear goal like make this website or make that website you know

#

my goal is to get a backend junior job by september

still laurel
#

Hi, I'm currently learning Django and wanted to allow users to edit and delete their own comments but I'm unsure how to go about doing this, I've tried looking online for answers but yet to find anything that makes sense to me. Any help would be greatly appreciated

rigid laurel
serene prawn
#

Django is quite dated too, but all frameworks are similar, so you shouldn't have much problems with it either

#

Focus on learning about (Rest) API's and SQL

mystic wyvern
#

Hi guys i've been learning django for almost 2 years i've cover most of concepts that relate to web dev like, rest api and the front end use react Js
Idk when I can take my first job bcz everyday I found something new to learn

rigid laurel
mystic wyvern
ocean slate
rigid laurel
rigid laurel
#

A little. Your best bet is to just ask the question here and hope someone with relevant experience comes across it

ocean slate
#

How can I make changes to flask app after deployment

#

if I want to add new tables and some features by using html css on site(flask app) which is hosted then how can I achieve this without loosing records of the existing database on the serve

inland oak
mystic wyvern
inland oak
#

The book more or less recommend what to read next

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied mute to @inland oak until <t:1651171691:f> (9 minutes and 59 seconds) (reason: attachments rule: sent 8 attachments in 10s).

white stratus
#

!unmute 370435997974134785

lavish prismBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @inland oak.

inland oak
#

Sigh

white stratus
#

Might want to share less links per message lol

inland oak
#

dammit. whole message is gone

inland oak
white stratus
#

Uno secundo

inland oak
# mystic wyvern wdym about code quality?
  1. learn what are the data structures and algorithms, book Groking Algorithms
  2. Learn how to git https://learngitbranching.js.org/
  3. Learn 5 best practices about Git, try for them to sink into your soul https://deepsource.io/blog/git-best-practices/
  4. Learn how to unit test your code, book Unit testing Principles practices and patterns (+ start to use Pytest if you did not yet)
  5. Learn advanced unit testing: TDD, with TDD kent beck book (recomended in the previous one)
  6. Read what is clean code (the book named simiarily, author Robert Martin)
  7. Start learning what is Design Patterns (and parallely somewhere what is inheritance and other OOP things, but technically the design patterns book should be good intro), with book Head First Design patterns
  8. Start reading Clean Architecture in your code (author Robert Martin)
    (---alternative path for starting from reading clean code and few others the book --- https://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670 Code Complete by McConnel, instead of reading Robert Martin, some people say McConnel is more readable, shrugs)
  9. (Bonus-Backend only) Reading about transforming monolith to microservices book by O'reilly
  10. (Bonus-Backend only) Building microservices O'Reilly
  11. (Bonus-Backend only) Reading about building event-driven microservices O'reilly
  12. Advanced Code Quality bonus: Reading stuff about Domain Driven Design (original author Erik Evans)
#

P.S. and a bit of infrastructure tools at least bare minimum. How to use docker and docker compose to setup your local dev env

mystic wyvern
#

Thanks a lot💓

mystic wyvern
inland oak
inland oak
mystic wyvern
inland oak
#

you can't use even curl there?

#

😱

inland oak
#

perhaps reseting it to low consuming in resources Linux

#

something like Lubuntu/Xubuntu

mystic wyvern
inland oak
mystic wyvern
mystic wyvern
inland oak
mystic wyvern
#

I try a lot but in vain

inland oak
#

use as main dev machine 🤷‍♂️

#

life will be easier

mystic wyvern
inland oak
mystic wyvern
#

Ok I will install it very soon

#

Thank you man u helped me a lot

inland oak
ionic raft
# mystic wyvern But I want os that fit to my pc

I use WSL 2.0 in Windows 10. You need to turn CPU virtualization on in bios (if it's not already on). After that, you have a great Linux box inside Windows, including full on SSH authentication if you want

mystic wyvern
#

i use win 7 (:

ionic raft
# mystic wyvern i use win 7 (:

In that case, I am very sorry 😦

Win7 is a deprecated OS. I appreciate that we are sometimes constrained in such choices, but remaining on Win7 opens you to a whole host of security issues and vulnerabilities. Windows is dodgy enough as it is. Being on an unsupported flavour, that's a whole different level of risk, for many, many reasons.

My suggestion, learn Linux, start with an accessible Linux Desktop distribution and move away from Win7 if $ is the constraint.

hidden marten
native tide
#

If you have an app that hosted on localhost. how do you connect it to a server

daring jay
native tide
daring jay
native tide
#

The app is like Django called otree. It generates urls for players to play games

hidden marten
digital osprey
#

How to resolve this error in django

dusk totem
#

!traceback

lavish prismBOT
#

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

dusk totem
#

Since it's Django, please use 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.pythondiscord.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.

digital osprey
#

how to resolve this error please help me

serene prawn
full badger
#

hey do you guys know how to link a python file to html

#

like run a .py file on html

wooden ruin
dusk thorn
#

Can Anyone help me with this Javascript Question, The question already print out an output

function main() { 
    var year = parseInt(prompt(), 10); 
    var month = parseInt(prompt(), 10); 
    var day = parseInt(prompt(), 10);

console.log(getWeekDay(year, month, day));
} 
function getWeekDay(year, month, day) { 
    var names = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; 
    var d = new Date(year, month, day); 
    console.log(d)
    //Function start
}
main()
dusk thorn
#

The output is already working just need to find the date from output

serene prawn
serene matrix
#

Hello I need some django help please.

My logout works well except when used from a model based view.

For instance when you're in someone's profile, it says it can't find the url because it checks for:

localhost/app/<primarykey>/logout

Instead of

localhost/app/logout

Def logout(request):
logout(request)
app.views.logout(request)

All this code is from my head but it's pretty accurate. Please suggest something you think might be wrong

manic frost
#

Can someone share their experience in adding warnings to HTTP responses? For example, to warn about deprecations or nearing rate limits. I've seen that there's a deprecated 'Warning' header, but it seems like something unrelated

#

I guess the main issue is how do you make people consider these warnings.

#

Send a "ping" warning and require an acknowledgement on it?

#

Or some other header like X-Warnings-Acknowledged: 3

manic garnet
#

Anyone who likes PHP here?

waxen tulip
#

Hi, Im trying to change the background color of a section by clicking a button (“button 1”), then when I click another button (“button 2”) , it turns the same background section a different color. I’m attempting to use the sec2.classList.add(“color”) for one button , then for the other button I used sec1.classList.toggle(“other color”). The two buttons are supposed to toggle the two colors of the section back and forth, but I’m not entirely sure how the toggle method works.

normal nacelle
#

What languages does a full stack web dev use?

rigid laurel
#

JavaScript/TypeScript for the front end is by far the most common, JS/TS are also both fairly common on the backend, but pretty much any language can be used for backend web dev, so: Golang, Python, Java/other-JVM-langs, C# etc are all very common

#

but if you're looking for one language that makes up the entire stack, then your only realistic option is JavaScript

frank shoal
rigid laurel
#

JS is incredibly common for Rest APIs, and pretty nice to use for it

serene matrix
# normal nacelle What languages does a full stack web dev use?

I guess just start and you'll end up with a "languages". You don't choose a language, the language chooses you.
If you're working on something eventually you'll meet a language that'll make your heart race and your fingers jitter. And then you'll end up settling down with the language after a number of daylight dates and sleepless nights with it. You have your frustrations no doubt and sometimes it'll feel like the language is trying to ruin your sanity, you might even threaten to walk away to leave the language for its cousin but you won't because this language is really the one. Eventually after all the stress, the language will finally come around and you'll see that all the fuss was just a simple misunderstanding. And you'll be in love once more.
Trust me... I know.

#

I just had to🙈

sour tulip
#

Hi guys! What I should learn fastAPI or Django?

#

Btw I have 0 knowledge about APIs, should I learn it before web development?

native tide
#

Are there any particular projects you want to work on, or jobs you want to apply to, etc? That would affect what you should learn

#

They are two different tools, each with things they are better suited for, so there isn't a right answer here

sour tulip
#

I see, there are not projects I want to work on tbh
I just want to learn more because every job request web development

#

Knowing only python is not enough to get a job

native tide
#

What you learn will depend on what the job wants. In general, fastapi is a newer and popular technology, so some employers may want you to know that. Others might want you to know stable technologies, or technologies they are already using such as django. Some employers will care about neither and want something completely different (javascript, java, c-sharp, ...)

Django is also larger in general than fastapi, but that may not be relevant to you.

devout sparrow
#

Hi

#

ANyone can help with adjusting margin of html

#

I want to do smth like dis

frank shoal
#

looks like a table

devout sparrow
#

This is what I have now

#

I am not sure how to adjust it

#

I tried adjusting margin

#

This is what I have

sour tulip
devout sparrow
#

@frank shoal

frank shoal
#

bootstrap should be doing it all for you.

devout sparrow
#

Can u help

#

adjust the margin

frank shoal
#

Try commenting out all your table css. Maybe use the bootstrap defaults

devout sparrow
#

whr

#

can u help

frank shoal
#

oh wait, this isn't about the table. It's about the table's margin.

devout sparrow
#

its about the

#

table floating in the middle

#

I want it to not touch the edge

frank shoal
#

wrap the table in a <div class="container">

devout sparrow
#

I want it to have space between the

#

whr

#

OHHH

#

IT WORKS

frank shoal
#

Why are you using bootstrap 3?

devout sparrow
#

Notsure

#

I copied the template

#

Omgg

#

u r life saviour

#

@frank shoal ❤️

native tide
#

pycharm community is good?

frank shoal
#

yes

#

but no javascript support.

#

pycharm professional includes javascript

daring jay
open sierra
#

so i am trying to scrape 3 urls, different pages of different websites although all have the same contents. however, this only scrapes the first page. i cannot share the 3 urls but know that the 3 urls are all correct

URL = ["url 1", "url 2", "url 3"]
gpu = input("Enter desired GPU ")
maxPrice = input("Enter max price ")

for url in range(0,2):    
    page = requests.get(URL[url])
    soup = BeautifulSoup(page.content, "html.parser")
    results = soup.find(class_="list-wrap")
    container = soup.find_all("div", class_="item-container")

    print()
#Test 3080 for 1000

    for containerElement in container:
        brandingElement = containerElement.find("div", class_="item-branding")
        titleElement = containerElement.find("a", class_="item-title")
        title = str(titleElement.contents)
        priceElement = containerElement.find("li", class_="price-current")
        price = str(priceElement.text)
        ratingElement = containerElement.find("i", class_="rating")
        if gpu in title and price <= maxPrice:
            for char in title:
                title = title.replace("[", "")
                title = title.replace("]","")
                title = title.replace("'", "")
            for char in price:
                price = price.replace("\xa0","")
                price = price.replace("–", "")   
            print(title.split("GDDR")[0])
            print(price.split("(")[0])
            if ratingElement != None:
                rating = brandingElement.find("i", {"class":"rating"})["aria-label"]
                print(rating.capitalize())
            else:
                print("No rating")
            print()         
#

i fixed it by increasing the size in range

carmine cipher
#

Hey guys , I am a full stack web developer , I want to switch to mobile app with java and kotlin . Assume I am a hardworking person then how long that can take me to learn it and make a app on my own ?

native tide
#

I even tried to track the test db, but I don't even see the records 😦

hidden marten
#

🤷‍♂️

#

does sqlite have nested transactions or something?

native tide
#

I don't know.
But I tried switching to a Postgres db, and it's the same thing lol

#

I just don't get it ahahahahahah

#

Thanks for trying !

hidden marten
#

one option could be to turn on debug logging for all sql statements and reason from there @native tide

native tide
#

I'll try that rn

#

I found something interesting @hidden marten, care to know ?

hidden marten
#

sure?

ionic raft
# native tide pycharm community is good?

PyCharm Community is good. It'll get you core IDE functionality. However, I switched to Pro because I like the expanded support. I've tried VSCode, Sublime and PyCharm, and when it comes to Python I've yet to see anything better than PyCharm. In particular, the suggestions it makes for ORM queries in particular has taught me a lot and saved me much time.

tiny ermine
#

hi guys, this is the functionality i'm trying to achieve,

<form>
                <button type="submit" class="btn btn-primary btn-lg" onclick="dataButtonClick()">Get Data</button>
            </form>

            <div class="card">
                <div class="card-body">
                    <p id="data field"></p>
                </div>
            </div>


            <script>
                function dataButtonClick() {
                    var data = JSON.parse('{{ get_data([1, 34, 12, 76, 18, 22])|tojson }}');
                    var p = document.getElementById("data field");
                    p.textContent = "data"
                }
            </script>

however, when i test this on my flask server, it appears in the thing for 1 second, then it disappears

hidden marten
#

wait dataButtonClick is not sending a request to flask. flask templated the data into the html in the initial page load

tiny ermine
#

huh

hidden marten
#

also are spaces even allowed in ids? I think you want data-field instead @tiny ermine

tiny ermine
#

im just very confused as to how to do this

tiny ermine
#

I have a generator that returns a dictionary of data

#

every time the user clicks the button

#

I want the next value to be in that card below the btuton

#

can you help me please

#

i have been stuck on this for a long time and I can't understand what to do

#

even after searching

hidden marten
#

you mean the generator yields a dict?

#

can you show the gen?

tiny ermine
# hidden marten can you show the gen?
def bubble(array: list) -> dict:
    index_length = len(array) - 1
    swap_counter = -1
    while swap_counter != 0:
        swap_counter = 0
        for i in range(index_length):
            yield currentframe().f_locals
            if array[i] > array[i+1]:
                array[i], array[i+1] = array[i+1], array[i]
                swap_counter += 1
        index_length -= 1
hidden marten
#

are you sure you don't just want ```js
const data = JSON.parse('{{ get_data(...)|tojson }}');
let index = 0;
const p = document.querySelector('#data-field');
p,textContent = data[i];
function dataButtonClick() {
i++;
p.textContent = data[i];
}

hidden marten
#

you need to elaborate. "doesn't work" doesn't tell us anything

tiny ermine
hidden marten
#

ok... is there an error in the devtools console?? what happens instead?

tiny ermine
#

it only shows get requests

hidden marten
#

not the terminal running flask. the browser's devtools console

tiny ermine
#

still nothing

shell dragon
#

Hello

#

Anyone familiar with django?

fossil kayak
#

Sup guys anyone know selenium….

#

Uhh if u do pls dm me

#

I need help clicking a button….

#

Sounds simple but it’s not I’ll explain in dms

#

Uhh so if anyone knows selenium pls pls pls dm me and help me out

#

Thanks

river glen
#

Can someone help me: I want to be able to detect when a web browser is done loading a tab, opened by the webbrowser module.

#

I don't own the website I just open it through python. (just p.s.)

native tide
native tide
native tide
#

uhh

#

can't help then lmao. i'm myself not familiar with selenium at this point

native tide
river glen
#

oh

#

when i was researching my issue I saw a lot of selenium

native tide
#

lmao

#

so your main issue is just to find out if page has been loaded?

river glen
#

yes

#

more specifically to wait until then but thats simple enough

native tide
#

🤔 i see

#

nvm even i'm seeing a lot of selenium shit on google related to this

river glen
#

ikr

native tide
#

uh yeah

river glen
#

I dont understand it either

#

any suggestions?

#

@native tide ^?

native tide
#

uhh idk honestly

river glen
#

k

native tide
#

looks like you need to get grip of selenium in this case

river glen
#

ok

native tide
#

other than this. i've no idea

river glen
#

k

#

thx

viral pumice
#

Hii, I have some questions regarding discord oauth2 that i am not sure i understand it right, and i am not sure where to ask so i asked here

cold wagon
ionic moss
#

Hi guys İ am trying to deploy a django app with, when i type "git push heroku master"on cmd on windows 10, it gives me this error. anyone can help

mental summit
ionic moss
#

i have tried "git push heroku main", i have tried to dowload "psycogp2" again.

#

but it didnt work

#

thanks anyway

trail axle
#

what’re backends for?

#

is it solely for databases?

dusk portal
#

git push --force

#

@ionic moss

#
def index(request):
    data={
        'name':'Aryan',
        'age':18
    }
    return JsonResponse(data)```
#
@api_view(['GET'])
def index(request):
    data={
        'name':'Aryan',
        'age':18
    }
    return Response(data)```
#
class Index(APIView):
    def get(self,request,*args,**kwargs):
        data={
        'name':'Aryan',
        'age':18
        }
        return Response(data)```
#
class Index(generics.ListAPIView):
    def get(self,request,*args,**kwargs):
        data={
        'name':'Aryan',
        'age':18
        }
        return Response(data)```
#

4 ways

#

of doing

#

same thing

#

wtf should i do

#

(context drf)

dusk portal
#

u'll be more clear

dusk portal
#

but what about these three

#

which method is better

#

n which method should i use

#

for whichcase whichone is better

trail axle
#

well i find people doing stuff like a todo app in just backend
and then i looked at fastapi (which is backend?) and it’s very different

dusk portal
#

more likely

#

related to database

#

but not actually only the db

#

it's a theory

#

just see
treehouse video on yt of backend

#

n u will get

#

better understanding

trail axle
#

no i just never use databases so that's a good enough answer

jaunty depot
#

hey guys
I'm trying to query my database for some records and add their content to a dictionary

def get_cat(cat):
    products = Product.query.filter_by(category=cat).all()
    prod_list = []
    listofdict = []
    product = {}

    for prod in products:
        product['name'] = prod.name
        product['id'] = prod.id
        listofdict.append(product)
        prod_list.append(prod.name)

    print("list of dict:", listofdict)
    print("prod list:", prod_list)
    
    return jsonify(prod_list)

however this code returns such output:
list of dict: [{'name': 'banan', 'id': 7}, {'name': 'banan', 'id': 7}, {'name': 'banan', 'id': 7}, {'name': 'banan', 'id': 7}] prod list: ['daktyl', 'jabłko', 'konfitura jagodowa', 'banan']

I can't see what I'm doing wrong - I don't want my dictionary to have only copies of the last element of the list - I wanted to have a list of dictionaries for each element

#

when I add print(product) inside of loop then it prints out each dictionary correctly
but why they are not appending to the list but only the last gets appended four times?

unborn flame
#

Create a new dict in each loop. The way it is now, you are creating a single dict, creating multiple references to it in the list and just keep overwriting its contents.

jaunty depot
#

damn it worked ❤️
thank you so much

#

ahh now I understand it
thank you also for explanation

covert yew
#
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(150), unique=True)
    username = db.Column(db.String(150), unique=True)
    password = db.Column(db.String(150))
    first_name = db.Column(db.String(150))
    last_name = db.Column(db.String(150), nullable=True)
    date_joined = db.Column(db.DateTime(timezone=True), default=func.now())
    
    following = db.relationship('Follower', backref='user', passive_deletes=True)
    followers = db.relationship('Follower', backref='user', passive_deletes=True)
    
    
class Follower(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    author = db.Column(db.Integer, db.ForeignKey('user.id', ondelete="CASCADE"), nullable=False)
    user = db.Column(db.Integer, db.ForeignKey('user.id', ondelete="CASCADE"), nullable=False)

how can I make a relationship to the same table twice and should I create a table for that or user something else?

agile pier
#

hii guys, does anyone know how to get the user's leetcode stats using api?

plucky wadi
#

How i do solve Permission denied when running django makemigrations command.(migrate command works tho )

serene prawn
lavish prismBOT
#

9. Do not offer or ask for paid work of any kind.

calm plume
#

@barren dust As was said, please don't advertise yourself here.

thorn igloo
dry obsidian
#

So in my public folder I have all these favicons to support most of the platforms. However they take up a lot of space (they have a size of 40 kb combined).

#

When I visit my website on my computer will all the favicons get downloaded?

#

So will it affect my website response time or is it the same thing as having only a favicon.ico

covert yew
thorn igloo
#

what is author there?

covert yew
#

follower is the person that follows

#

and the user_id is the ones he follows

thorn igloo
#

ahh, i see

covert yew
#

any other way to do this?

#

like any better way

thorn igloo
#

im thinking about that

covert yew
#

should it even be a model in the database or its just not efficient doing that?

thorn igloo
#

it makes sense to model it

#

but here's my idea

#

why not give a user a follower id for example

#

and basically use that to track who they follow if that makes sense

covert yew
#

I see

thorn igloo
#

like in your follower table, you'd have

#

the user id foreign relationship

covert yew
#

like generate another id like the normal one just for following?

thorn igloo
#

when someone follows you just use the follower id

#

let me reword that

#

user id for foreign relationship
follower_id to see follower

covert yew
#
id = db.Column(db.Integer, primary_key=True)
follower_id = db.Column(db.Integer, unique=True, autoincrement=True)
thorn igloo
#

yea, i guess

#

doesnt need to be a primary key tho

#

but it works i guess

covert yew
#

why not?

#

ohh

thorn igloo
#

you already have id as primary

thorn igloo
#

yea, nice

covert yew
#

how do I make it auto generate it?

#

like the primary key?

thorn igloo
#

auto increment?

#

let me google how to do that in sqlalchemy

covert yew
#

btw do you have any tool to see/edit databases?

thorn igloo
#

just use autoincrement=True in the field

covert yew
#

alright ty <3

thorn igloo
#

yeah, i use dbeaver

#

very nice UI

covert yew
#

1 second ill check that out

#

alright thank you

hard whale
#

Ayo guys, is peewee still working learning or it's old and replaced by newer more flexible orm?

worn crystal
#

is Smtplib a good way to send verification emails to users?
I have a flask app that I want to send verification emails to users when they sign up and so I was curious to know if this is a "good" way of doing it

fickle fox
#

Hey guys, how would you save image file in db with flask

pallid hill
#

Does anyone know how to disable Javascript and WebRTC in PyQtWebEngine? I want to have a privacy centered Web Browser that I made so that's why I want to know this.

obtuse robin
#

im not sure how if you mean something downloaded

steady turret
#

x3 is it possible to write in the browser console with quart/flask ?

#

would be fun

native tide
#

I can't find a damn download for the tor client and I can't use my linux machine

gusty marsh
#

@crisp hound bro i m back and this time u cant bl

native tide
#

why can't I find it lmao

viral pumice
#

hiii, i have a question about django
so i have a link that will redirect the user to this
http://localhost:port/reviews/edit/<user_ID>/<review_ID>
from http://localhost:port/reviews
inside the html file

 <div class="card-header">
                      <ul class="nav nav-tabs card-header-tabs">

                            <li class="nav-item">
                                <a class="nav-link" href="{{current_path}}edit/{{user.id}}/{{review.id}}">Edit</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link " href="{{current_path}}delete/{{user.id}}/{{review.id}}">Delete</a>
                            </li>
                      </ul>
                  </div>```
The issue is that i can't make the same thing as `current_path` inside the `urlpatterns`
```py
urlpatterns = [
    path("", views.home),
    path('admin/', admin.site.urls),
    path("home/", views.home),
    
    path("/edit/<int:user_id>/<int:review_id>", views.edit_review, name="edit_review"),
    path("/delete/<int:user_id>/<int:review_id>", views.delete_review, name="delete_review"),
]

is there a way to make it inherit from the current path?

native tide
#

Join me in this fun interactive session that will help you in exploring Data Analysis and also walk you through the details of the Microsoft Learn Student Ambassador Program.

Key Takeaways:-
-Introduction to Microsoft Learn Student Ambassador
-Overview of what is Data Analysis
-Creating Microsoft Excel Dashboard
-Introduction to Microsoft Power BI
-Quiz and Giveaways
-Q&A

EVENT DETAILS -
Date - 8th May 2022
Day - Sunday
Time - 5:00 PM IST
Duration - 1 Hour
Platform - Microsoft Teams
Event Host - Aditi Gulati (Alpha Microsoft Student Ambassador)

If anyone is interested then DM for registrations

craggy flax
#

Guys can anyone give code for image encryption using convolutional neural networks?

covert yew
sonic sky
#
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>PyScript Hello World</title>
<link rel="icon" type="image/png" href="favicon.png" />
<link rel="stylesheet" href="../build/pyscript.css" />
<script defer src="../build/pyscript.js"></script>
</head>
<body>
Hello world! <br>
This is the current date and time, as computed by Python:
<py-script>
from datetime import datetime
now = datetime.now()
now.strftime("%m/%d/%Y, %H:%M:%S")
</py-script>
</body>
</html>
#

Now this is cool

random spindle
#

django or flask

#

whats better

#

for beginner

abstract birch
ruby sorrel
abstract birch
ruby sorrel
#

can't say which is technically better as far as how low level implementations of built in classes and their methods but i think flask is quicker to get up an running from scratch.

agile pier
#
query = """
      { 
        matchedUser(username: "adityag28") {
          username
          submitStats: submitStatsGlobal {
          acSubmissionNum {
          difficulty
          count
          submissions
          }
        }
      }
    }
    """

variables = {'username': 'sanskarchandra26'}

url = 'https://leetcode.com/graphql/'
r = requests.post(url, json={'query': query, 'variables': variables})
print(r.status_code)
print(r.text)
#

how do I use the variable username in the query?

ruby sorrel
agile pier
#

this is the graphql api format
i m also very new to this

ruby sorrel
#

ive never heard of graphql but there must be some sort of way to key inside it.
like how you would access, purple (for example) in this this dictionary

my_dict = {
    "fruits": {
        "apples": "red",
        "grapes": "purple",
        },
    "name": "adityag",
    }

by doing

print(my_dict["fruits"]["grapes"])
#

or are you trying to do it from string in the query variable? coz i would just use .split() or regular expressions

native tide
abstract birch
#

anyone that knows flask can help me to understand how to build my project?
I want to build some kind of interactive database from mongodb, that will allow to filter stuff and the ability to export

native tide
dusk portal
#

Heyyy

native tide
#

under source code

#

the site is there

#

check it out

#

no

#

why not

#

why not ninja

fickle fox
#

anyone knows how to fix this bug??

#

<form action='{{url_for("create_com")}}' >
<input type="text" name="comment" id="content">
<input type="submit" name="submit" value="Post">


</form>


@app.route("/create/comment/<int:id>", methods=["GET", "POST"])
def create_com(id):
    if request.method=="POST":
        comment=request.form("coment")
        author=current_user.fname
        makecomment=Comments(ccontent=comment, cauthor=author, blogid=id)
        db.session.add(makecomment)
        db.session.commit()
        return redirect(url_for("open", id=id))
    else:
        comments = Comments.query.filter_by(blogid=id).all()
        return render_template("post.html", comments=comments)


#

werkzeug.routing.BuildError: Could not build url for endpoint 'create_com'. Did you forget to specify values ['id']?

#

aaah nvm fixed it

hollow dune
#

could anyone suggest an app for making html pages like in VS or Rider, where you just drag and drop parts and arrange them and its simple, cuz i dont want to have to write everything by hand.

rich warren
abstract birch
rich warren
keen inlet
#
import functools

user = {"username":"jose", "access_level":"admin"}

def make_secure(func):
  @functools.wraps(func)
  def secure_function(*args, **kwargs):
    if user["access_level"] == "admin":
      return func(*args, **kwargs)
    else:
      return f"no admin premmission for {user['username']}."

    return secure_function

@make_secure
def get_password(panel):
  if panel == "admin":
    return "1234"
  elif panel == "billing":
    return "seper secure password"


print(get_password("billing"))
#
 line 23, in <module>
    print(get_password("billing"))
TypeError: 'NoneType' object is not callable
#

Hi someone can help me to figure out why the error occurs 🙏

autumn creek
random spindle
#

javascript or python for web dev

dense cedar
#

¯\_(ツ)_/¯

dense cedar
random spindle
#

back end web dev

dense cedar
#

You know Django?

#

I won't prefer anything nor I am going to compare. But Django would be a great choice

random spindle
#

i know pure/default JS

#

i know python

#

thats it

#

i dont know any other type of JS like node

#

just the default js

dense cedar
#

Okay

random spindle
#

JS is a beautiful language

#

but i know python more than JS so maybe django is better choice

frosty aurora
#

I am returning to confess that sesssion management isn't easy, but I'd also like to add that it's mostly because I didn't realize how many possible states in the flow existed

ember fossil
#

anyone know how to stop a uvicorn (fastapi) server cleanly in code?

dense cedar
#

In Django, You generate a boilerplate and start writing code

#

Wheras in node you have to start from scratch. Or you can use express to serve webpages

dense cedar
#

Wheras in node you have to start from scratch. Or you can use express to serve webpages

stone sandal
#

What’s a boilerplate

native tide
#

as a noob, I was scared of mixing JS with python so I focused on python alone.

frosty aurora
frosty aurora
#

!doc sys.exit

lavish prismBOT
#

sys.exit([arg])```
Raise a [`SystemExit`](https://docs.python.org/3/library/exceptions.html#SystemExit "SystemExit") exception, signaling an intention to exit the interpreter.
native tide
frosty aurora
native tide
frosty aurora
#

It'll be much less friction on the syntax, but if you already don't know some of the "weirdness" behind how a browser works then I'd spend a little extra time seeing how they do stuff that's usually a bit of a headache to do from inside WASM, e.g. messing with the DOM API

native tide
#

looking forward to the day we can run pygame on browser

agile pier
#

how do I return image/svg+xml in django?

golden hamlet
gleaming heron
#

Hey guys

#

I waw learn basic of python now i wanna learn back end so which is the best? I will learn python or shift on php,laravel?

#

Which language is best for back end and easy too

serene prawn
#

And if you want to learn php

gleaming heron
#

No I anna learn python if php will easy than python so I can switch 😁

#

I wanna learn easy language 😶

dusty mesa
#

Has anyone completed the web Development course by johns Hopkins University on coursera?
I'm Looking to get into web dev and found this course as a starting point

dusk portal
#

which type of view is more preferable while using django rest framework

#

it has alot of options

#

function based views

#

class based views

#

n generic class based views

#

tbh i'm using function based views

#

in my django web application

#

but some people told me on rest framework class based views r better

#

so what should i do

#

any suggestion pls

#
def index(request):
    data={
        'name':'Aryan',
        'age':18
    }
    return JsonResponse(data)```
#
@api_view(['GET'])
def index(request):
    data={
        'name':'Aryan',
        'age':18
    }
    return Response(data)```
#
class Index(APIView):
    def get(self,request,*args,**kwargs):
        data={
        'name':'Aryan',
        'age':18
        }
        return Response(data)```
#
class Index(generics.ListAPIView):
    def get(self,request,*args,**kwargs):
        data={
        'name':'Aryan',
        'age':18
        }
        return Response(data)```
#
class Index(generics.ListAPIView):
    queryset=BlogPost.objects.all()
    serializer_class=BlogPostSerializer

class Index(APIView):
    def get(self, request, *args, **kwargs):
        qs = BlogPost.objects.all()
        serializer = BlogPostSerializer(qs, many=True)
        return Response(serializer.data)```
#

same output

#

what should a person use

#

n does it matter

latent cosmos
#

hey, I am trying to set a local JS file:

<script src="https://static.cdn-website.com/SOME_JS.min.js"></script>

so instead this https I am giving my path with that js with the same content as that from domain, and it does not work, all animation on the website stops... Any idea how is it possible, if the local content is the same as that on domain?! Local path is correct too!

#

(please ping me when answering, appreciate help)

serene prawn
#

APIViews are for something more complex

#

Didn't really use function based views though

gusty sky
#

Hello guys, I have problem with CORS when trying to reach backend with frontend. I am using Vuejs (+ router and axios) and Fastapi (+uvicorn, pymongo). I have tried to allow it in axios via axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*'; but it does not work. I have tried to allow it at the backend level as well, but it still does not work.

dusk portal
serene prawn
#

I don't work with pure django 🙂

gusty sky
serene prawn
#

I wish i never worked with django or drf

gusty sky
dusk portal
#

why

#

so what u guys use

serene prawn
dusk portal
#

ohh

#

u also use fastapi?

#

ohh it's getting popular i see

gusty sky
#

its the fastest.

dusk portal
#

when i was a flask dev everybody was saying learn django

serene prawn
#

FastAPI > Flask

dusk portal
dusk portal
#

now when i'm good at django

#

ppl are saying learn fastapi

dusk portal
#

n today itself i got a call from a hr

#

he said he want me to work on flask

#

i mean wtffff man

serene prawn
dusk portal
#

why am i so unlucky

serene prawn
#

But fastapi is just better 🙂

dusk portal
#

ohh

gusty sky
dusk portal
#

but ig

#

companies dont use

serene prawn
dusk portal
#

fastapi

serene prawn
gusty sky
#

Daaamn son. u got me, thanks

dusk portal
#

ohh

serene prawn
#

actually a lot of companies use fastapi

dusk portal
#

ohh

#

so

#

it's worth it

#

to learn fastapi

#

i was thinking to learn js n then MERN

serene prawn
#

Again, it's similar to flask but has more features overall

dusk portal
#

but i was quite sad cuz

#

my python basics r better

#

it's fast then js too? @serene prawn

serene prawn
#

I'd recommend learning python to comfortable level first, then picking up different languages shouldn't be that hard

#

iirc js is faster, but that's usually not the main concern

gusty sky
# serene prawn 127.0.0.1 != localhost

Uncaught (in promise) 
Object { message: "Network Error", name: "AxiosError", code: "ERR_NETWORK", config: {…}, request: XMLHttpRequest, response: XMLHttpRequest, stack: "" }```
rigid laurel
dusk portal
#

it isn't hard but i don't like it cuz

#

i worked so hard

#

learning frameworks

dusk portal
#

like django

#

flask

#

etc.

serene prawn
serene prawn
gusty sky
serene prawn
#

That's not a good metric to choose a language, otherwise everyone would be writing machine code

dusk portal
#

Initial release date: 5 December 2018

#

damnnn

#

new

gusty sky
#

but in backend i shoud allow 8081 which is frontend, shouldnt I?

dusk portal
#

actually why not
i'm surely gonna

#

learn it

serene prawn
gusty sky
#

i tried both f.e. and b.e. ports, still nothing 😄

serene prawn
#

Also you can check Host header on your request

gusty sky
serene prawn
#

Try checking host header

#

If your frontend is on http://localhost:8081 then it should work 🤔

#

ah

#

trailing slash?

gusty sky
#

yup now it works.

origins = [
    "http://localhost:8081",
    "http://127.0.0.1:8081"
]
#

removed the slashes at the end

#

😄

hazy night
#

Im not quite familiar with this tag.. I know its pulled from a javascript function for it to pop up but not sure how i can select it since its an alert that doesnt last long

#

does anyone know a bit about it? im using selenium at the moment and am trying to automate a process where when this pops up it would wait a couple seconds before beginning my loop again

#

nevermind i froze DOM to pull the javascript in time

agile pier
#

does anyone know how does github readme markdown work?

#

if anyone know pls help

native tide
#

so i have a html page ive already created and css, how can i use django to grab the values of the form? without using widgets etc in views.py

hollow dragon
#

been learning Flask for a couple of weeks now and trying to tweak this to-do-list with new features. i was able to add "timestamp" as a new class, migrate it to the db and using Flask-Moment to show it on the app

#

i know its not super interesting but coming from only frontend, working with Flask is so interesting

gusty lynx
hollow dragon
#

thank you mate! yeah, I'm going to learn django down the road, I'm just focusing on Flask at the moment because I've got an internship opportunity and the company works in Flask. The internship starts in a couple of months so I'm trying to learn as much as possible beforehand. 🙂

hazy night
#

Hi, im looking for help with selenium.. Below is my current code(snppet) and what I wish to do is that if txn_e is present wait, but if it is not continue to the sell and confirm and loop on until txn_e is present to then wait (atm i have it set for 5 second).

The tricky part with this is that uni-toast is an alert of sort that appears when your balance is below a certain amount. but when i use my try/except it returns as false(empty element list).

while True:
    create_order = driver.find_element(By.XPATH, '/html/body/uni-app/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-view[4]/uni-button').click()
    try:
        txn_e = driver.find_elements(by=By.CLASS_NAME, value='uni-toast')
    except NoSuchElementException:
        print("No element found")
    else:
        print("Below $5.. Please wait")
        time.sleep(5)
    if txn_e is True:
        sell = driver.find_element(by=By.XPATH, value='/html/body/uni-app/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-view[7]/uni-view/uni-view/uni-view[6]/uni-button[2]').click()
        time.sleep(10)
        confirm = driver.find_element(by=By.XPATH, value='/html/body/uni-app/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-view[8]/uni-view/uni-view/uni-button').click()
        time.sleep(10)
inland oak
#

/html/body/uni-app/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-view[8]/uni-view/uni-view/uni-button writing using long path like that is unacceptable

#

u a supposed to use only some sort of identifiers from the end of the path

#

like unique class of the uni-button object

hazy night
#

im using the full xpath

inland oak
#

u a using it wrongly

hazy night
#

is there a way to shorten it?

inland oak
#

yes

#

correct path would be looking out of 1-3 sub levels at the deepest end of the DOM. Not the 10 of them like u have from the root

hazy night
#

got it, like me clean it up some. thanks for the tip will be back

inland oak
#

usually people find objects by #unique_id or .class_names

#

if it is possible to find only by .class_names, and they are more than one of them, they add going into it from the parent class

#

something like

#

.uni-view -> .unit -> button

#

correct usage requires knowing CSS basics at least, how to use CSS selectors basically, or just finding objects by class/ids in Selenium, it is possible without CSS selectors i think

terse niche
#

hey does anyone know how can we host django website and mysql database for free? Please

terse niche
hollow dragon
random spindle
#

is udemy any good

hollow dragon
#

i mean

#

I would rather read books about the topic

#

and apply the knowledge on a project

hazy night
#

ive cleaned up most of my XPATH while also working on the loop at hand.. but im having issue with shortening this XPATH for a button
element : <uni-button data-v-2fa3158e="" class="" type="primary">Sell</uni-button>
XPATH : /html/body/uni-app/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-view[7]/uni-view/uni-view/uni-view[6]/uni-button[2]

Ive written //uni-view[7]/uni-view/uni-view/uni-view[6]/uni-button[2] and a couple variation but continue to get the element is not interactable error

inland oak
nimble wraith
#

Hello python community! : )

I have my little Flask project and it's currently running with the given IP.
I did some research because I want to use a custom domain but couldn't find any helpful answers ("PyCharm Flask use custom domain"). So I want to ask you guys if you could help me to use a custom domain in PyCharm using Flask.

Thank you!

inland oak
#

Just find smth like Namecheap how to configure A record

#

Or better get domain in Cloudflare perhaps

nimble wraith
#

I'm currenly using cloudflare to connect my IP to the domain

#

But I dont know how to use it in pycharm

swift sky
#

is it possible to save a pdf to a tempfile

#

im having a hard time finding good examples online

#

everything i see tries to write a string to bytes

native tide
#

What does a cli actually do? Does it pass arguments to the server?

frank shoal
#

Like with a flask cli?

#

@app.cli.command() will run the command on the host you ran it on. The only connections it will make are ones you specifically make and database connections if needed.

random spindle
frank shoal
#

!resources

lavish prismBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

frank shoal
#

if you buy a book on full stack, it will be outdated in a month

random spindle
#

yeah

hollow dragon
#

lmao

#

I learned everything about Flask thanks to Miguel's book

#

even deployment

frank shoal
#

You could use yoursite.localhost

nimble wraith
hollow dragon
#

Ah ight

frank shoal
#

Who is your provider?

nimble wraith
#

dns server is cloudflare

frank shoal
#

No, that's your dns server, not your provider.

#

ex: you can use google, aws, namecheap, etc

nimble wraith
#

I am using PyCharm to create the flask application and use cloudflare as an dns server

frank shoal
#

What exactly are you trying to achieve? Putting a hostname in the url and getting your app?

#

i.e http://your-awesome-host.com/

nimble wraith
#

I am trying to connect my flask applicatrion with a domain

#

yes

frank shoal
#

You will need a host then.

nimble wraith
#

wich for example

frank shoal
#

heroku can host a single app for free with limited capabilities.

nimble wraith
#

I am already using an KVM vServer for that

frank shoal
#

on your local machine?

nimble wraith
#

on dashserv, but there are so many other hosters

frank shoal
#

Is it a static ip?

#

You'll need to pay 5 euros for it, plus there's a renewal fee each year.

nimble wraith
#

I do already own some domains

frank shoal
#

And you're trying to link it to pycharm?

nimble wraith
#

exactly

frank shoal
#

are you trying to debug your production machine?

#

Is it pycharm community or professional?

nimble wraith
#

community

frank shoal
#

pycharm community doesn't support remote connections

nimble wraith
#

well I should have known that before, are there any other IDEs that support it?

frank shoal
#

vscode does

nimble wraith
#

thank you for letting me know that

frank shoal
#

via an extension

#

btw, your question should have been:

I have a server. How do I connect Pycharm to it?

#

An alternative could be to mount your code onto a shared NFS volume, though that tends to impact file watcher performance.

native tide
frank shoal
#

cli is just for the flask cli

bitter ravine
#

Can anyone help me fix this error. The django modules don't seem to be here, although I have done every setup right

remote prawn
#

is django installed and is your ide pointing to the correct venv?

charred cedar
#

how do i use math.ceil() in my jinja template? I want to round up a passed param, but don't want to make another parameter to send to the template.

remote prawn
#

what is the context in which you want that implemented

#

in your template

charred cedar
#

<h2>Only {{ math.ceil(contract_remaining.weeks) - 1 }} more {{ today.strftime("%A") }}s left!</h2>

It's a countdown that has a dataclass passed to it that i access in the template. This is the line im trying to round up.

remote prawn
#

and the dataclass passes succesfully?

charred cedar
#

oh ya, this works just fine

#
    <table>
        <thead>
            <tr>
                <th>Days</th>
                <th>Weeks</th>
                <th>Hours</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>{{ contract_remaining.days - 1 }}</td>
                <td>{{ contract_remaining.weeks }}</td>
                <td>{{ contract_remaining.hours }}</td>
            </tr>
        </tbody>
    </table>
bitter ravine
#

Anyway, thanks. I've figured it out😉

remote prawn
#

no worries

remote prawn
#

sorry if that doesn't help anything at all

#

iirc {{}} is for variables and {%%} is for other stuff

charred cedar
#

hmmm but its both a variable and "other stuff"

#

ill try it out

#

nah, didn't work

remote prawn
#

well I suck sorry man

charred cedar
#

No you dont lmao thanks for trying though <3

remote prawn
#

my very cursory google search seems to indicate that the best practice is to put the maths in your view and then pass it to the template but that doesn't sound like it would work well for you

charred cedar
#

i went ahead and did something similar, i dont think its possible for a template to do anything more than stock python, the rest needs to be passed to the template

acoustic summit
#

Hi guys

#

what library you recommend to convert list object to array json?

charred cedar
#

do you mean write a list to json text file?

acoustic summit
#

i need response to get method with list json

charred cedar
#

ill need more context

acoustic summit
#

I retrive a list object from database using sqlachemy

#

i need build an endpoint than reponse with list json

remote prawn
#

do you really mean list or do you mean dict

#

if list I think it's doable if you define fields and then add teh values

#

then you can easily go from dict to json

#

as a dict it's basically already json

acoustic summit
#

aList is a list of objects

remote prawn
#

oh ok yeah you are creating a dict

acoustic summit
#

I look a library to convert aList to list json

remote prawn
#

or rather you are making a list of dicts

#

feels like you could just make a dict that then gets those values then json.dump that dict

#

or return it or send it to a client or w/e

#

in which case you would skip the list step

jovial mortar
#

Anyone have the slightest idea as to why the hell fastapi is rounding my integers to the nearest 10 in responses?

#

occasionally it rounds to 4 or 6 as well

native tide
# frank shoal cli is just for the flask cli

I see, I have a lib that is based on Django. But doesn't have the wsgi.py and uses asgi, it has the asgi.py inside the lib of it's package but also Uvicorn and starlette. Been trying to figure out how to attach it to the web.config in place of the wsgi_handler

jovial mortar
jovial mortar
#

I've able to consistently reproduce with numbers greater than ten quadrillion (10_000_000_000_000_000), with reproduction as simple as ```py
import random
from typing import List

from fastapi import FastAPI

app = FastAPI()

@app.get("/", response_model=List[int])
async def test():
values = [random.randint(10_000_000_000_000_000, 100_000_000_000_000_000) for _ in range(5)]
for value in values:
print(value)
return values

remote prawn
#

could have something to do with length of the long int

#

it it really rounding when you inspect it

#

or is it just displaying rounded

#

also do you have a legit need for values that large?

#

@jovial mortar ?

jovial mortar
#

yeah

#

i use snowflake values for my object ids, identically to how twitter and discord do it

#

i suppose if it's just to do with the displaying of the values, I can work around it, but it's quite annoying

remote prawn
#

I can't be sure if it is, personally, but it seems like that's what is happening

jovial mortar
remote prawn
#

ahh

jovial mortar
#

Maybe I should serve the user IDs as strings and convert them back when received by the client

#

I guess that's why discord does it that way

remote prawn
#

that'd make sense

#

kind of annoying to have to do tho

#

sorry bro

jovial mortar
#

yeah it is. thanks though

hexed solstice
#

Hi Pythonistas! Got a question that might be a silly one, please bear with me!

I'm hoping to move all my web development into Python. I know that Django is a great framework for full-stack, and Flask and FastAPI are close seconds. But I wonder is there a way to do full-stack development with Python where there's a good separation of concerns? I don't really want to build everything in the 1 framework since that makes it hard to scale and use the API for different things. But I haven't really found a Python front-end framework.

What's out there? What have you found, or used before? Or is it just pretty common for Python web devs to do everything under 1 framework? Or do we use python for API and server, and something else for front end?

Cheers!

inland oak
#

Frontend in python is not possible.
Just some limited frontendiness with Jinja2 templating library
And possible usage of vanilla js, jQuery or even statically linked Vue.js. that is it. For full frontend go to js frontend frameworks installed with js package managers

hexed solstice
#

Thanks for your answer so far @inland oak ! I've come to realise that there aren't any python frontends, and it's all just templates. Looks like Python is all backend only.

I am familiar with Vue and React so I guess I'll stick with them!

This definitely helps me keep to the separation of concerns.

obtuse robin
#

are you able to submit a form to flask without the page refreshing

#

there are going to be multiple forms in this one page i want to build but they arent very "refresh worthy" and are simple things just intended to give a bit of data to my database

inland oak
obtuse robin
#

are you able to add something to a database using just vanilla web js?

#

i thought i would need to know node js or somethign

inland oak
#

Yes u can, but it is much more painful than using full frontend framework with node.js stuff

#

Vanilla js syntax is horrible

#

But it can do the trick

obtuse robin
#

i see

#

wait so is what im trying to do too much of a hassle with flask? should i just make the app with node js instead, or am i able to use both

inland oak
#

Obviously, js just calls backend endpoint of backend framework in order to make request to db

inland oak
obtuse robin
#

ah okay

inland oak
#

Essentially yes. People use backend and frontend at the same time.
Backend can be python, frontend is js

#

U can of course try doing it in flask, but u code will become more and more shitter with every addition of vanilla js

static patio
#

Hi everyone, is anyone familiar with apache2?

nimble wraith
#

Okay, now after I know pycharm commumity doesnt support virtual connections and I should use vscode, I've installed it and it works again but my question is still the same; How do I connect my flask application with my dns server to use a custom domain?

small coral
nimble wraith
inland oak
inland oak
#

Get server from something like DigitalOcean for example

serene prawn
inland oak
#

Haproxy for load balancing!

#

Nginx for reverse proxy and static assets server ;b

serene prawn
#

Traefik doesn't have anything to do with caching really? It's a reverse proxy

inland oak
#

some features are available in free version, and some only in premium

#

to my understanding Traefik just has more free to use features for caching

serene prawn
#

Traefik is mainly a reverse-proxy, i'm pretty happy with it compared to nginx

#

Mainly because of service discovery in docker swarm / docker compose

#

With configuration looking like this:

version: "3"
services:
  my-container:
    deploy:
      labels:
        - traefik.http.routers.my-container.rule=Host(`example.com`)
        - traefik.http.services.my-container-service.loadbalancer.server.port=8080
native tide
#

So

#

I am going to use djiango

#

wish me luck

serene prawn
native tide
#

I know a free hosting service but I would like to know what is your recommendation

serene prawn
#

I don't really like django but if you're building a personal website using templates then it's ok

#

You can get vps for like 5 eur/mo

native tide
#

u prefer flask?

#

or u use nodejs/php

serene prawn
#

It's just kind of outdated

#

I mainly use fastapi

native tide
#

outdated 0-0

#

It is actually newer than some api

serene prawn
native tide
#

anyway

#

fastapi

serene prawn
#

It's 16 years old, fastapi is quite new

native tide
serene prawn
#

It's really hard to use compared to fastapi though

native tide
#

I see

#

so the take here is hard to use

#

thx for the opinion

serene prawn
#

Well, it doesn't use modern features like type annotations, async (it's getting there), so it's somewhat outdated

native tide
#

I have never tried fastapi so I cant tell

#

but flask is indeed easier than djiango

serene prawn
#

Especially the DRF that most people use with django to create rest api's

#

Also orm is lacking support for more complex queries

native tide
#

Wow fastapi is a 2018

#

3 years old

native tide
serene prawn
#

Many people use it actually

native tide
#

Hmm

serene prawn
#

Compared to django it's really just easier:

class Item(BaseModel):
    name: str
    description: str | None = None
    price: float
    tax: float | None = None


app = FastAPI()


@app.post("/items/")
async def create_item(item: Item):
    return item
native tide
serene prawn
#

You can use assembly then 😅

native tide
#

I am a little bit higher so I am using c/c++

#

C++ to be exact*

#

anyway

serene prawn
#

I meant to say that fastapi is more modern but it's a microframework meaning you'd have to choose an orm and implement things like authentication yourself

native tide
#

You vouch for fastapi

serene prawn
#

But if it's a personal site that would just render some templates i think you can use literally anything

native tide
#

so fastapi is minimal*

serene prawn
#

Yep, like flask but on steroids

native tide
serene prawn
#

Seems pretty simple, go with django

native tide
#

Yup

#

unfortunately not 100% static

#

if it was I would just host on github

native tide
serene prawn
#

Yep, your app seems pretty simple, for something more complex i'd use fastapi

native tide
#

I see

gusty hedge
#

it actually depends on your needs. If your app needs intensive use of SQL operations and you don't want to take too much decisions about code organization, choose Django. If your business logic is simple and don't need "all batteries included" or DB is nonsql, choose, FastAPI, Flask, etc

native tide
#

🔋 🔋

#

I dont know if they are good or not

serene prawn
native tide
#

maybe staying minimal is good and simpler

serene prawn
#

django orm isn't that great

native tide
gusty hedge
native tide
#

in my current situation flask, djiango, and fastapi are all usable*

serene prawn
gusty hedge
#

yeah, there are plenty of options out there. Stuff to have in mind when choosing (at least what I follow): skills, time/budget and requirements

serene prawn
#

I'd argue if it's a long-term project it's better to use something minimal that you can tailor to your needs

gusty hedge
#

I'd seen people forcing Django to work with nonsql DB. Definitely money is not a problem 😂

native tide
#

idk but i see djiango in itself is worth learning

serene prawn
gusty hedge
serene prawn
native tide
cloud path
#

how do i check if some letters are in the name of a string? like "Book", and I give an input of "Bo", and it will give me the field that contains "Book"?

gusty hedge
native tide
#

if money was not the issue then idk

gusty hedge
#

yeah, I don't know...

serene prawn
#

.NET Core is actually quite good, i'm not sure why you'd move to python

gusty hedge
#

yeah, no idea. My guess is that some tech lead convenced bosses

native tide
#

in conclusion it is a djiango

serene prawn
#

jk, just take a look at it, compare with django

native tide
native tide
#

is there any good lecture about djiango or a straight to documentation

#

djiango is old so I think its documentation will be less modern

serene prawn
native tide
native tide
#

while fastapi is quite young so I am less likely to get alot of guides

serene prawn
#

Take a look at sqlalchemy docs

native tide
serene prawn
native tide
#

before even learning

native tide
serene prawn
#

It doesn't mean turing complete

#

I can build all types of web applications with python

native tide
serene prawn
native tide
serene prawn
#

or starlette, sanic, etc

#

In my opinion django tries to handle too much things (templating, orm, migrations) not the best way

#

And there's a lot of boilerplate involved

native tide
native tide
#

another question

#

any free hostin service

#

Im goin on budget now >->

serene prawn
#

~5 eur

native tide
#

thats about 40+ usd yearly

#

anyway

#

thx for suggestion

serene prawn
#

Well, yeah, but you can host multiple websites there

#

And 40 usd early isn't that much 🤔

native tide
native tide
serene prawn
#

Again, you can host multiple services on single vps

native tide
#

Yes

#

I also believe that website will be on very low traffic for a while

#

Fine

#

JUST another subscription, this the last one!

#

@native tide can you tell us what your goal is, there might be something we can suggest

native tide
#

It would be static right ?

serene prawn
#

Blog type thingy

native tide
#

Ooh

#

I will leave it dynamic ;-;

#

I mean I can use Jekyll

#

I can help you do that using Wordpress

#

Yeaa

gusty hedge
#

vultr has $2.5/m boxes

native tide
#

I have wordpress set on local

native tide
#

Im actually not good at frontend

#

I understand how CSS works, but design and frustration is endless

#

whoever created CSS is evil

#

You can pick a theme in Wordpress

#

no need to design it yourself

#

elementor is op

#

I will come here to ask alot of things about webdev >->

#

I hope i get help and thanks in advance

serene prawn
native tide
#

I mean I met alot of people who dislikes wordpress

fleet vector
#

Which tool is commonly used for serverless in Python?
Zappa, chalice, serverless framework or the aws sdk?

native tide
fleet vector
#

I used the serverless framework while working in JS but it's mainly a js libary

serene prawn
amber ember
fleet vector
amber ember
#

I'm speaking from experience

serene prawn
#

You can make a mess in both django/flask

amber ember
#

it's always humorous to me to see devs that think "Django is too heavy" and then 18 months later they've recreated it, but worse

serene prawn
fleet vector
native tide
amber ember
#

I guess I can only speak from my personal experience and what I've seen

#

definitely seen some bad apps that started out with that exact mindset

serene prawn
amber ember
#

then ended up getting ported to the big framework eventually

serene prawn
#

You can use whatever orm you like, and you don't really need anything else

amber ember
#

lol ok

#

I see you speak for all devs and all apps everywhere

serene prawn
#

That's just my opinion

#

@amber ember
Django has many batteries included but they're bad quality 🙂
ORM is lacking support for many use cases - cte's, no direct support for group_by or having, long spanning string joins, e.g. user__comments__text__contains=...
Test system - why? We have pytest
No type annotations

DRF specific:
ViewSets are great, unless you need something more than CRUD
Again, no type annotations?
Serializers - they're old, pydantic does validation better, also for some reason serializers responsible not for just validation your data but also for creating it

native tide
serene prawn
#

I'm not saying django is bad, it just has a lot of problems or outdated features

#

and some of them aren't addressed for years

native tide
#

outdated >> dated/experimental/beta-testing

#

I would vote for old features rather than new ones, personally

native tide
serene prawn
native tide
#

I prefer old because normally it is well tested and most of its problems already have a solution somewhere on the internet, and importantly it is more stable and consistent

serene prawn
#

Well, fastapi/pydantic are well tested

#

They're not week old

native tide
#

but trying new ones is not bad either

#

modern solutions are also usually smarter

#

what I like about the new apis is the ease of use

serene prawn
#

Django started quite a long ago, when we didn't have modern features like async or type annotations, so it lacks in these
As i said async is coming to django, but it's a bit too late

serene prawn
native tide
#

ya

serene prawn
#

I don't know