#web-development
2 messages · Page 226 of 1
Maybe you can show an example of how to do it properly?
no idea why it's not on fastapi docs
stmt = select(Item).where(Item.id == some_id)
item = (await session.execute(stmt)).one()
session.delete(item)
await session.commit()
thanks, i'll try that! and for update?
Hm, actually it's better to use scalar or just raw delete statement here, HTTP Delete should be idempotent
i couldn't find method for it
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
stmt = delete(Item).where(Item.id == some_id)
await session.execute(stmt)
await session.commit()
Select your model from database, update it's properties and save it
@serene prawn so anything in-between would be blind to the password
Well, using encryption here sounds ok, but how exactly do you prevent replay attacks?
Also in case of mitm attack won't attacker be able to substitute his own public key?
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
I think in this case encrypting password at client side doesn't really make sense?
if i remember it right, the client gets nonce and some other data which is signed with the service's private key and checks the signature before it uses that data to encrypt the password and reply to the service
Even google sends password as plaintext to the server/backend, i don't think encryption at client side makes any sense here
You're trying to mitigate mitm attacks by encrypting the password, which you're still vulnerable to (at least it seems like to me)
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 🤷♂️
it depends on where the mitm would happen and in what way
mitb/c would be a problem that we can't really protect against
i don't think anyone can that has the larger public as a user base
@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()
from sqlalchemy import delete
and device_delete = delete(Device).where(device.id == location)
Device, not device
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?
Strange.. Doesn't delete anything
change Device.id to Device.location?
I have GET for /device/{location}, won't they conflict?
facepalm -_- , I need some rest i guess
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
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)
I personally preferer sqlalchemy
any benefits?
i just like the docs for fastapi and sqlmodel, very newbie friendly
good examples are the best way to learn
sqlmodel uses sqlalchemy under the hood, it just simplifies model creation
also sqlalchemy docs have a lot of examples for different use cases
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 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
use http client, like httpx or requests
@serene prawn
import json,urllib.request
data = urllib.request.urlopen("url").read()
output = json.loads(data)
print (output)
somewhat like this?
Hello, I am using xhtml2pdf to convert my template into html but bootstrap doesn't seem to work, any ideas?
yo bois, should i first do flask and then django?
i'm done with python basics so i wanna move on to web-dev
i think yes django is bit confusing start with flask
I would advise doing whichever one best fits your needs. I don't think there's much value in learning flask purely for the sake of learning, there might be value in learning Django for the sake of it though
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
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
Pursuing specific Frameworks doesn't seem like the most efficient way to get there. But there are more Django jobs than the are Flask ones, although still not very many
I'd say it doesn't really matter, i'd go for FastAPI, it's more modern than flask and you shouldn't have much problems migrating to flask later if you have to
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
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
My suggestion would be to just start applying ASAP rather than worrying too much about your skills - and make sure you're comfortable talking about what you do know. Unless you have a degree or relevant experience, the hardest part really will be getting in the door for an interview, so you probably want projects on Github or something to demonstrate your skills
Freelance dosen't refine my skills to be my first experience in work?
you have to use relationship tables for that
I'm not 100% sure on what you're asking, but yeah, freelance would be relevant experience and would help you refine your skills
Hello, do u know flask?
A little. Your best bet is to just ask the question here and hope someone with relevant experience comes across it
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
Learn Code Quality ;b Knowing Django is nothing without knowing Code Quality
wdym about code quality?
Yeh that what I meant
The book more or less recommend what to read next
: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).
!unmute 370435997974134785
:incoming_envelope: :ok_hand: pardoned infraction mute for @inland oak.
Sigh
Might want to share less links per message lol
dammit. whole message is gone
could you copy paste me it to DM?
Uno secundo
- learn what are the data structures and algorithms, book
Groking Algorithms - Learn how to git https://learngitbranching.js.org/
- Learn 5 best practices about Git, try for them to sink into your soul https://deepsource.io/blog/git-best-practices/
- Learn how to unit test your code, book
Unit testing Principles practices and patterns(+ start to use Pytest if you did not yet) - Learn advanced unit testing: TDD, with
TDD kent beckbook (recomended in the previous one) - Read what is
clean code(the book named simiarily, author Robert Martin) - 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↵ - Start reading
Clean Architecturein 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/0735619670Code Complete by McConnel, instead of reading Robert Martin, some people say McConnel is more readable, shrugs) - (Bonus-Backend only) Reading about transforming
monolith to microservices book by O'reilly - (Bonus-Backend only)
Building microservices O'Reilly - (Bonus-Backend only) Reading about building
event-driven microservices O'reilly - 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
I already knew some of these like oop and algorithms and design patterns and more. But I will get into the other concepts
Thanks a lot💓
anyone
?
sorry for annoying you,my pc is not running docker bcz it's weak is there any alternative
U a welcome.
P.P.S. I just remembered I missed some important book from the list. When starting some projects, there is necessarity in planning... how to plan developing projects, and transforming user/business requirements into what needs to be done from technical side?
System analysis and design book is the answer https://www.amazon.com/Systems-Analysis-Design-Alan-Dennis/dp/1119496500
Sorry, no. Docker is already lightweight solution in virtualizations. How weak your PC is?
Mmm..., it's so weak that you can't run curl on it (:
docker run -it alpine:latest /bin/bash
you can't use even curl there?
😱
May be you have just a lot of garbage installed on PC?
perhaps reseting it to low consuming in resources Linux
something like Lubuntu/Xubuntu
Yeah I'm suffering a lot
i think PC like is just not meant to be use. I mean common, ancient 2 core CPU machines from 12-15 years ago, are already enough to work with
Yep sometime I watch tutorial without practice
I think I can't use a lot of tool bcz of win7
hey... you can't install docker to win7
get used to Linux. If you are backend dev, you meant to use Linux
use as main dev machine 🤷♂️
life will be easier
But I want os that fit to my pc
Linux can fit to anywhere windows fits and even more
Excellent. Linux Linus Torvalds approves
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
I'll give a shot
but wait a second ..
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.
@mystic wyvern you can upgrade win7 to win10 for free via https://go.microsoft.com/fwlink/?LinkID=799445 and then use WSL that way
If you have an app that hosted on localhost. how do you connect it to a server
Are you looking to host your application on a cloud hosting service?
I have a Windows 10 VM with windows server 2012 installed
Hmmm...not sure I understand what you are trying to do.
Attach the app to run on the server. I can run it on local but need to attach a url to it so other people can use it.
The app is like Django called otree. It generates urls for players to play games
@native tide re #help-coconut message, the error is about rows in the join table, not in the workspace table
Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.
How to resolve this error in django
!traceback
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.
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.
install debug toolbar?
you can't, this also presents lots of security vulnerabilities
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()
I need to find the Dateday from the question
The output is already working just need to find the date from output
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
This is open in #help-kiwi please.
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
Anyone who likes PHP here?
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.
What languages does a full stack web dev use?
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
The only reason I'd use JS/TS on the backend is for SSR, but that's technically frontend.
JS is incredibly common for Rest APIs, and pretty nice to use for it
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🙈
❤️ 😁
Hi guys! What I should learn fastAPI or Django?
Btw I have 0 knowledge about APIs, should I learn it before web development?
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
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
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.
looks like a table
This is what I have now
I am not sure how to adjust it
I tried adjusting margin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
This is what I have
Hmm I'm not sure what job I want but I'm sure web development is every time more important and requested.
I think I should start with something to have a little of knowledge of web development, what do you recommend me to start off with?
I didn't know fastAPI until I saw it here but I was interested in Django
@frank shoal
bootstrap should be doing it all for you.
Try commenting out all your table css. Maybe use the bootstrap defaults
oh wait, this isn't about the table. It's about the table's margin.
wrap the table in a <div class="container">
Why are you using bootstrap 3?
pycharm community is good?
Ah…got it. Not sure how to do it for that use case, off the top of my head
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
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 ?
Yes understood.
But what I'm wondering is: why does it only happen in the context of tests ?
It wouldn't make sense to just call clear on all relationships when I'm testing.
Also, I tried to clear these relationships from the django admin site, and when I track them in the db, the relations get deleted correctly
I even tried to track the test db, but I don't even see the records 😦
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 !
one option could be to turn on debug logging for all sql statements and reason from there @native tide
sure?
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.
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
wait dataButtonClick is not sending a request to flask. flask templated the data into the html in the initial page load
huh
also are spaces even allowed in ids? I think you want data-field instead @tiny ermine
okay
im just very confused as to how to do this
because this is my website
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
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
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];
}
it doesn't work
you need to elaborate. "doesn't work" doesn't tell us anything
it don't show up on the website
ok... is there an error in the devtools console?? what happens instead?
not the terminal running flask. the browser's devtools console
still nothing
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
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.)
yes i'm 'familiar' to some extent
💀 no one gonna DM u uk.. just drop your question already.. or open a help channel
I did….servers kinda slow
r u talking to me?
i said 'selenium' it's related to IamNotDrunk guy above
ikr
uh yeah
uhh idk honestly
k
looks like you need to get grip of selenium in this case
ok
other than this. i've no idea
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
https://discord.com/developers/docs/topics/oauth2#authorization-code-grant-refresh-token-exchange-example
in this function, what should i pass?
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
hey guys i need help w/django #help-cherries
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
I’m not sure but I think it might be because the branch is now called main not master
i have tried "git push heroku main", i have tried to dowload "psycogp2" again.
but it didnt work
thanks anyway
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)
ignore the 1st method cuz it isn't part of drf
but what about these three
which method is better
n which method should i use
for whichcase whichone is better
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
the server side stuff
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
no i just never use databases so that's a good enough answer
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?
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.
damn it worked ❤️
thank you so much
ahh now I understand it
thank you also for explanation
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?
hii guys, does anyone know how to get the user's leetcode stats using api?
How i do solve Permission denied when running django makemigrations command.(migrate command works tho )
Create custom join condition. for following you'd join on user.id == follower.user, for followers you'd join on follower.author ( i guess )
@barren dust As was said, please don't advertise yourself here.
why do you need two relationships for 1 table if i may ask?
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
I want to create a follow model for following users and I want to have follower_id and user_id
what is author there?
the person with a follower
?
ahh, i see
im thinking about that
should it even be a model in the database or its just not efficient doing that?
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
I see
like generate another id like the normal one just for following?
when someone follows you just use the follower id
let me reword that
user id for foreign relationship
follower_id to see follower
id = db.Column(db.Integer, primary_key=True)
follower_id = db.Column(db.Integer, unique=True, autoincrement=True)
you already have id as primary
fixed
yea, nice
just use autoincrement=True in the field
alright ty <3
Ayo guys, is peewee still working learning or it's old and replaced by newer more flexible orm?
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
Yeah i guess so
Hey guys, how would you save image file in db with flask
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.
if the image is something online, you can save the url as something in the db
im not sure how if you mean something downloaded
I can't find a damn download for the tor client and I can't use my linux machine
@crisp hound bro i m back and this time u cant bl
why can't I find it lmao
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?
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
Guys can anyone give code for image encryption using convolutional neural networks?
Its not generating anything, I tried googling it but I found nothing
Run Python code in your HTML.
<!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
I'd like to know that too
easier to teach django according to dr charles severance. but both are good.
I've a DB on mongo cloud already working with some other application, but I want to make web version of that application, which would be better ?
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.
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?
is your query variable supposed to be json? coz it looks like a function to me
this is the graphql api format
i m also very new to this
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
http://xijcct7hu2gu6pkozsaf6ugytlz2bcl3bups3rxaozylj5gkz3s3a6ad.onion/
Check out my first onion site
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
You mean sudo apt install tor doesn't work?
Heyyy
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
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.
that sounds like you need some database library like MongoAlchemy, pymongo, etc..
do you know some kind of example of this thing? Like how to implement it on web application with flask or django?
no clue, ask to #databases and once you know how works you can try to implement it in flask
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 🙏
return secure_function should be indented to the same level as the make_secure body. you have it indented one level too far.
note that that error may be easier to spot with 4-space indents instead of 2
ok
javascript or python for web dev
¯\_(ツ)_/¯
You can choose both
but dont they do the same thing?
back end web dev
Yes. It's just about writing a code
You know Django?
I won't prefer anything nor I am going to compare. But Django would be a great choice
nah i dont know django
i know pure/default JS
i know python
thats it
i dont know any other type of JS like node
just the default js
Okay
JS is a beautiful language
but i know python more than JS so maybe django is better choice
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
anyone know how to stop a uvicorn (fastapi) server cleanly in code?
Now node is awesome but Django is much easy
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
Wheras in node you have to start from scratch. Or you can use express to serve webpages
What’s a boilerplate
Yeah, came here to talk about this
as a noob, I was scared of mixing JS with python so I focused on python alone.
Would be much more excited about an all-Python stack if it didn't mean adding 5 seconds of latency on page load
Is there anything wrong with sys.exit()
!doc sys.exit
sys.exit([arg])```
Raise a [`SystemExit`](https://docs.python.org/3/library/exceptions.html#SystemExit "SystemExit") exception, signaling an intention to exit the interpreter.
anything else that you notice that's bad? I thought of learning flask with brython.
If you're learning to learn, go for it! This tech stack is probably only going to get better over time, but I'd be surprised if employers are gonna be asking for Python frontend any time soon.
I haven't audited it thoroughly, but like any other new ambitious project, be ready to deal with "rough edges" like missing documentation
yeah, guess I have to stop nitpicking and try it. better than learning JS from scratch
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
looking forward to the day we can run pygame on browser
how do I return image/svg+xml in django?
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
Python is fine for backend, look whatever is more widely used in your area/country
And if you want to learn php
No I anna learn python if php will easy than python so I can switch 😁
I wanna learn easy language 😶
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
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
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)
Generic views are nice to use if you need to add pagination, etc quickly, i'd go for that in some cases
APIViews are for something more complex
Didn't really use function based views though
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.
ohh
don't u use function based views also while working with pure django (not drf)
I don't work with pure django 🙂
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/host/get_data. (Reason: CORS request did not succeed). Status code: (null).
I wish i never worked with django or drf
Now i am happy that I use fastAPI
why so
why

so what u guys use

its the fastest.
when i was a flask dev everybody was saying learn django
FastAPI > Flask
but people say
"wtf u're making web app in py == slow"
u will get gigs
now when i'm good at django
ppl are saying learn fastapi
Can any1 help me plz?
n today itself i got a call from a hr
he said he want me to work on flask
i mean wtffff man
You should add cors on fastapi side
why am i so unlucky
FastAPI and flask are quite similar
But fastapi is just better 🙂
ohh
origins = [
"http://localhost:8081/",
"http://192.168.0.105:8081/"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
127.0.0.1 != localhost
fastapi
We use it 😦
Daaamn son. u got me, thanks
ohh
actually a lot of companies use fastapi
Again, it's similar to flask but has more features overall
but i was quite sad cuz
my python basics r better
it's fast then js too? @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
Uncaught (in promise)
Object { message: "Network Error", name: "AxiosError", code: "ERR_NETWORK", config: {…}, request: XMLHttpRequest, response: XMLHttpRequest, stack: "" }```
If you do (or plan to do) a lot of web development, I'd recommend getting familiar with how CORS actually works. The key thing is that before you make a cross-site request, the browser will send out another OPTIONS http request to see whether or not the server supports CORS, and if the server doesn't respond it won't work.
port also matters
There's no place like http://127.0.0.1:8000
?
iirc js is faster
if __name__ == "__main__":
uvicorn.run('web:app',
host="127.0.0.1",
port=8000, # default port is 8000
reload=True)
That's not a good metric to choose a language, otherwise everyone would be writing machine code
but in backend i shoud allow 8081 which is frontend, shouldnt I?
Hm 🤔 I'm not actually sure, i think so
i tried both f.e. and b.e. ports, still nothing 😄
Does it work if you allow all origins?
Also you can check Host header on your request
well, yes
Try checking host header
If your frontend is on http://localhost:8081 then it should work 🤔
ah
trailing slash?
yup now it works.
origins = [
"http://localhost:8081",
"http://127.0.0.1:8081"
]
removed the slashes at the end
😄
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
does anyone know how does github readme markdown work?
https://github-readme-stats.vercel.app/api?username=adityagoel28&show_icons=true&theme=tokyonight
Like when adding this to the readme, it shows the stat
ig it works when the return type is svg
if anyone know pls help
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
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
wow thats great, looks neat in my opinion
i just straight up went for django when i wanted to learn web dev, didn't care about flask
but i think django would be kind of heavy for simple projects.
flask wouldn't be practical for large scale applications, but for simple projects like these, i think its pretty good
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. 🙂
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)
No idea what your question is, but I would prefer if you fixed how you find your values
/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
im using the full xpath
u a using it wrongly
is there a way to shorten it?
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
got it, like me clean it up some. thanks for the tip will be back
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
hey does anyone know how can we host django website and mysql database for free? Please
heroku?
can we host mysql database too?
as far as I know
any1 tried this course?: https://www.udemy.com/course/the-complete-web-development-bootcamp/
is udemy any good
i mean
I would rather read books about the topic
and apply the knowledge on a project
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
Give a reading to Head first CSS book
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!
Domain is not in anyway IDE or programming language attached
Just find smth like Namecheap how to configure A record
Or better get domain in Cloudflare perhaps
I'm currenly using cloudflare to connect my IP to the domain
But I dont know how to use it in pycharm
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
What does a cli actually do? Does it pass arguments to the server?
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.
yeah but books = $$$$ and hard to find
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
if you buy a book on full stack, it will be outdated in a month
yeah
sorry but what do you mean by: "custom domain in PyCharm"
lmao
if you want to deploy your flask project I'd recommend https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
I learned everything about Flask thanks to Miguel's book
even deployment
You could use yoursite.localhost
I'm actually trying to connect to a dns server
Ah ight
Who is your provider?
dns server is cloudflare
No, that's your dns server, not your provider.
ex: you can use google, aws, namecheap, etc
I am using PyCharm to create the flask application and use cloudflare as an dns server
What exactly are you trying to achieve? Putting a hostname in the url and getting your app?
i.e http://your-awesome-host.com/
You will need a host then.
wich for example
heroku can host a single app for free with limited capabilities.
I am already using an KVM vServer for that
on your local machine?
on dashserv, but there are so many other hosters
Is it a static ip?
Find your domain with this.
https://dashserv.io/domain-registrieren
ex
You'll need to pay 5 euros for it, plus there's a renewal fee each year.
I do already own some domains
And you're trying to link it to pycharm?
exactly
are you trying to debug your production machine?
Is it pycharm community or professional?
community
well I should have known that before, are there any other IDEs that support it?
vscode does
thank you for letting me know that
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.
I see, how do you attach it to an ASGI server like Daphne or Uvicorn.
cli is just for the flask cli
Can anyone help me fix this error. The django modules don't seem to be here, although I have done every setup right
is django installed and is your ide pointing to the correct venv?
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.
<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.
and the dataclass passes succesfully?
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>
I installed it in the virtual environment I created.
Anyway, thanks. I've figured it out😉
no worries
it's been a minute since I did this but I think you need to {% math.ceil(contract_remaining.weeks) -1 %}
sorry if that doesn't help anything at all
iirc {{}} is for variables and {%%} is for other stuff
well I suck sorry man
No you dont lmao thanks for trying though <3
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
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
do you mean write a list to json text file?
i need response to get method with list json
ill need more context
I retrive a list object from database using sqlachemy
i need build an endpoint than reponse with list json
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
oh ok yeah you are creating a dict
I look a library to convert aList to list json
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
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
FYI this only happens with larger numbers for some reason...
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
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 ?
well
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
I can't be sure if it is, personally, but it seems like that's what is happening
I actually just figured that out, and yeah it is.
ahh
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

yeah it is. thanks though
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!
Firstly, be careful with marrying python Frameworks. Better to try keeping your code isolated if possible from them.
Secondly, all Python Frameworks provide working as JSON REST API at least, then they serve as backend only
It is assumed that proper frontend will be made in React/Vue.js/Angular
Recommending Vue.js for Frontend part, as it is easiest to learn and work with
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
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.
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
With vanilla js, jQuery or with statically linked vue.js.
For a full power for that, to go into frontend frameworks
That is the purpose of js. Doing stuff without refreshing.
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
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
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
Obviously, js just calls backend endpoint of backend framework in order to make request to db
Literally answered just above you, to user RachelJ
ah okay
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
Hi everyone, is anyone familiar with apache2?
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?
You need to get a DNS record for yourself from a registrar
So I have a domain, use cloudflare as an dns server (I am using the A record type) and I have my Flask application. But I don't know how to connect my flask application with this record. Is it the IP adress from the "Running on: xxIPxx" print when running the application,..?
Nginx is better ;b I think it is just even more popular
U get server or PC with public IP accessable from outside world
U install your flask app there
U point your DNS records to this public IP.
Profit
Get server from something like DigitalOcean for example
Traefik 🤔
for caching!
Haproxy for load balancing!
Nginx for reverse proxy and static assets server ;b
Traefik doesn't have anything to do with caching really? It's a reverse proxy
does it? Nginx is reverse proxy but can be used for caching as well
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
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
What for?
for my personal website
I know a free hosting service but I would like to know what is your recommendation
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
why
u prefer flask?
or u use nodejs/php
?
I dont think it is outdated, it is among the young api
anyway
fastapi
It's 16 years old, fastapi is quite new
djiango is mature but not that old
It's really hard to use compared to fastapi though
Well, it doesn't use modern features like type annotations, async (it's getting there), so it's somewhat outdated
Especially the DRF that most people use with django to create rest api's
Also orm is lacking support for more complex queries
Is fastapi production ready ?
Yeah, i use it in production
Many people use it actually
Hmm
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
I have no problem with difficulty as long as it gets the job done
You can use assembly then 😅
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
You vouch for fastapi
Oh
I see
But if it's a personal site that would just render some templates i think you can use literally anything
so fastapi is minimal*
Yep, like flask but on steroids
templates, blogs, and most likely comment section
Seems pretty simple, go with django
wait not fastapi?
Yep, your app seems pretty simple, for something more complex i'd use fastapi
I see
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
I'd argue that it's better to not use django if you have any intensive sql operations or complex business logic
maybe staying minimal is good and simpler
django orm isn't that great
Honestly, i dont expect alot from a 3 years old api
yeah, it also depends on dev team skills. If writing and maintaining SQL statements is ok. Go for something lighter
in my current situation flask, djiango, and fastapi are all usable*
Or you can use sqlalchemy and don't touch sql directly at all?
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
Good point
I'd argue if it's a long-term project it's better to use something minimal that you can tailor to your needs
I'd seen people forcing Django to work with nonsql DB. Definitely money is not a problem 😂
idk but i see djiango in itself is worth learning
Well, it is, but it's just a bit outdated
if team is good to keep code organized. Otherwise it will be a mess. I'd seen teams in transitions from .NET and Java stacks moving to Python (using Flask) and result is a mess
It's not a problem with specific framework
why would they move out of .Net and java
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"?
I wasn't there when decision was taken. I got into the team a year later
maybe .Net and Java devs are just getting more paid
if money was not the issue then idk
yeah, I don't know...
.NET Core is actually quite good, i'm not sure why you'd move to python
yeah, no idea. My guess is that some tech lead convenced bosses
in conclusion it is a djiango
fastapi :D
jk, just take a look at it, compare with django
You really remind me of those who advertise Rust on the C++ server
this is said, I will keep it in mind
is there any good lecture about djiango or a straight to documentation
djiango is old so I think its documentation will be less modern
You should be able to find tutorials on YT, docs also should have a tutorial

haha
while fastapi is quite young so I am less likely to get alot of guides
Take a look at sqlalchemy docs
If you follow the documentation, you would be lost. There are a lot and lot of things that Django offer (Its Turing Complete), Start by focusing on what you need to do and do a project based learning.
Django is a framework, what do you mean by turing complete? 😅
wow so it is just set up a project and face the problems head on
before even learning
You can build all types of web applications using Django
It doesn't mean turing complete
I can build all types of web applications with python
Yup, facebook proved that
Facebook doesn't use django though
Not all frameworks offer everything required, Like Django does. In that context it is turing complete
Well, that doesn't mean you can't use something else instead, like flask or fastapi
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
Yup
Instagram was built using Django, Not sure what changed recently
yeaa
another question
any free hostin service
Im goin on budget now >->
I didn't really use free services but basic vps is quite cheap
~5 eur
You can try AWS Lightsail, VPS for 3.5 USD per month (First 3 months free)
thats about 40+ usd yearly
anyway
thx for suggestion
Well, yeah, but you can host multiple websites there
And 40 usd early isn't that much 🤔
how does that compare with google cloud
subscriptions keep stacking up though

Again, you can host multiple services on single vps
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
personal website
It would be static right ?
Ooh
I will leave it dynamic ;-;
I mean I can use Jekyll
I can help you do that using Wordpress
Yeaa
vultr has $2.5/m boxes
I have wordpress set on local
thanks
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
no no no
wordpress hater?
I mean I met alot of people who dislikes wordpress
Which tool is commonly used for serverless in Python?
Zappa, chalice, serverless framework or the aws sdk?

I used the serverless framework while working in JS but it's mainly a js libary
Didn't have any experience with serverless, mostly use fastapi/strawberry 🤔
The counterpoint being I've seen more than one Flask (and Sinatra on the Ruby side) app that just ends up being a shittier duct-taped version of Django/Rails
Most jobs want experience building API's on AWS and that's what I want to branch to. It was easy to do in Node but seems python is pretty lacking.
Ehm, not really
I'm speaking from experience
You can make a mess in both django/flask
You can AWS Lambda for that
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
How can you make it worse? 😅
The framework builds on Lamda and provides an interface. I guess it's not commonly used. Thanks still
By trying to make it simple I guess 😄
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
My coworkers find fastapi easier to use than django when building api's
then ended up getting ported to the big framework eventually
You can use whatever orm you like, and you don't really need anything else
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
Actually, it is good to have that enthusiasm and passion to promote an API or a programming language. This is one way to make it popular. As for the case with any open source project, the more popular it becomes the better it gets refined.
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
outdated >> dated/experimental/beta-testing
I would vote for old features rather than new ones, personally
I hope there are solutions and work around those problems uwu
Why? Is it better to work with serializers rather than pydantic/other models that would have type annotations?
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
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
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
You mean frameworks/libraries
ya
next year?
I don't know