#web-development
2 messages · Page 213 of 1
have anyone used lib called
django-private-chat
Do you know what a long is?
a long (generally) is a 64 bit integer.
it is not a long string.
no in this case i declared the model myself
the name is kinda confusing lol
oh, long is the name
yeah the long version of the url
You should still consider using a query parameter instead.
but then how can i retrieve it? i mean how can i pass it to the backend?
sorry if this sounds stupid btw, but i can't find anything online about this
query is always passed to the backend. It's usually in a request variable
Django Ninja - Django REST framework with high performance, easy to learn, fast to code.
I guess something like this. ```py
def do_something(request):
print(request.GET.get('url', ''))
run it again?
Just get the URL you are trying to get after the captcha is done. Not certain it will work but it's the first thing I would try
how do grab a jinja template variable in my javascript
Celery question:
What is the ‘socket_timeout’ parameter in BROKER_TRANSPORT_OPTIONS used for?
For Redis
I am working with django. The app works fine locally but when I upload it on heroku I get the 500 error
hello, im trying to learn flask and read this on the documentation
$ export FLASK_APP=flaskr
$ export FLASK_ENV=development
$ flask run
will this command set anything permenent to my system? i don't know much about environment variables and i'll proly be deleting this flask app and creating new ones while learning and don't want it to leave any uneeded things on my pc
Should url encoding be done server or client side?
Anybody here using selenium and having a list of options you can pass in ChromeDriver? I've been checking the source code and so far I'm not seeing any enumeration.
Those changes will be reset on reboot. They also won't impact anything but Flask
In theory Options can be empty if you want but often you do need --headless and/or --no-sandbox depending on the environment
--no-sandbox removes extensions right?
The ones I'm attempted to use are --headless and --incognito
It's a bit lower level than that I guess https://www.google.com/googlebooks/chrome/med_28.html
Look under the hood of Google Chrome in this comics interpretation of key engineering decisions with art by Scott McCloud.
Ok so iirc it protects from malicious content. I'm using Selenium for webscraping so it's best if I keep both flags on?
Thank you!
Ayo fellas, wondering if it's possible to unescape html characters? Men&s;s converts to Men's on the website i'm parsing. html.unescape doesn't seem to conver it
Like I said, it may be required depending on your environment, so I have no idea of you need it or not
I'm trying to merge two django apps into one, I'm setting db_name in Meta to avoid moving tables, how would I merge the migrations from the now deleted app into the combined app?
heyo, short question i want to use python the requests lib to download a csv file from a website, the thing is, the download is triggered if a certain html element is clicked and prompts e.g. firefox dialog popup to save the file on disk, is this possible to automate with this python lib ?
It is, but a lot of people don't seem to know this and I myself did not. I figured it would be useful for people to know.
well its kind of like
having multiple youtube videos
opened
in the same browser
its kind of obvious the browser wont ask you to re-login
for every individual tab
If it's JavaScript you probably need Selenium but if it's just a simple request then requests should work. You might need to use developer tools to figure it out. Or show us the link if you can
in django i am passing a list to my template
list = [{'name':...,'url':...}, ...]```
so i wrote {% for i in list %}
can we use this
{{ i['name'] }}
yes but you access it with i.name
oh ok thanks :)
do we have to load anything in template to use {% set a = ... %}
does anyone have any ideas why I am unable to extract data from a simple form I made
The first picture is python file in relation to flask
The Second picture is html file with a form
Question, I'm not immediately doing web dev yet (I tend to ask questions ahead of time) but what's the difference between Cypress and Selenium
As far as I know, they're used for larger scale website testing in comparison to something like Jest but that's about it
Jest is for suiting for Unit and Integrations tests
Learn Jest first
Unit and Integration tests are giving more... quality/proffit for time investment into them
Unit tests are the fastest, precise, pointing to exact error location usually
Integration tests are showing how the service works in integration with other services
You can even write in some frameworks End to End tests too in them
with a help of framework additional libraries
Cypress and Selenium implement the most expensive tests that make at the same time the biggest impact, while being the longest to run, but their point that they make THE most identical last testing to production running. They can see what any other tests can't.
But they are a hell of expensive (in terms of time wasted for implementation, time running and maintanance) and not really even written in small projects usually
Unit and Integration tests are the most important and should be done first
Is there a way to get an app in a app store without paying?
So I should only use Cypress or Selenium for larger scale projects, and even then prefer Jest if possible?
U should use always Jest type of testing for all types of projects
and in projects that require a special quality / large projects and e.t.c. to add Cypress/Selenium testing in addition
Here is a regular propoprtion of amount of tests in a project to have quality testing
not really the real proportion is shown here, but you get the idea
Ah, thanks for giving me advice
how do i generate unique group names for consumers for individual chess games? i could have used pk but i don't want to store the game in db
django
That's not entirely true. Jest is a js testing library. You can certainly use it to perform integration tests too, though it's mostly used for unit tests with frontend libraries like react or angular.
The line between using jest and cypress can get a bit blurry when testing- do I unit test my ui component or just let cypress test it?
The difference is libraries like cypress run tests in the browser. So this is a good place to run tests from the perspective of the user- testing entire auth flows and what not
<@&831776746206265384>
this too
It’s also in #databases #data-science-and-ml #cybersecurity #user-interfaces
does anyone know why url encoding of something like www.google.com gives back the same string, but diango still doesn't accept it and throws a 500? how can i avoid that?
I created a registration form and i set up a few error messages
and i used this to display those messages
from django.contrib import messages
if not username.isalnum():
messages.error(request, "Username must be alphanumeric.")
return redirect("/register")```
but shouldnt the message be in Red background instead of just white
Hello guys I need some help the media query isn't working for me i'm using SCSS
aye
whats the problem here
json = {"state":"Online","devices":[{"type"="PlayStation","titles":[{"expiration":600,"id":TitleID,"state":"active","sandbox":"RETAIL"}]}]}
^
SyntaxError: expression expected after dictionary key and ':'
the problem stis in between "devices" and the type
what am I doing wrong
never mind it's fixed
I feel like the type="PlayStation" is the problem
You used a = instead of a :
how can I run and monitor a long running background job in flask?
Hi
I want to deploy a flask application with gunicorn on heroku. Should I keep app.run() in the app.py file or is not required because it says do not use run() in production env.
When u use gunicorn, app.run will be not used
Oh that means it won't cause problem if I just keep it there?
does anyone have any ideas why I am unable to extract data from a simple form I made
The first picture is python file in relation to flask
The Second picture is html file with a form
I think its because you've written methods in the form tag instead of method
oh shit
right
wait let me try change that
im getting this error still:
werkzeug.exceptions.BadRequestKeyError
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: ('url', '0')
any idea @west skiff
which line is this error for? i can't tell if its for those u sent above
Why did u put slashes at the end of tags
Ohh kk
uhhh im sorry @west skiff but someone ellse just helped me resolve the issue from another issue
my syntax was wrong in def(home)
but thank you so much for trying
Oh okay np
It should not
Heyooo... basically I've created a website in React, but as everyone knows, when creating a React project with npx it creates a 300 mb folder. My question is, how do I extract "only what I need"?
😳 sorry if this is stupid
You run npm run build and it would place everything you need into build directory
(django) in a consumer, does it stack the messages sent from client to server and then call recieve method for them? and does sending message in group with self.channel_layer.group_send calls the method of type use the same stack? I am asking cause, if a client sends a move repetedly then this code will just crash, since it will allow both or all the legal move they try to play cause it updates the self.board when the method of type is called after sending a msg with self.channel_layer.group_send?
def move_if_legal(self, san):
if self.board.turn != self.client_colour:
return
try:
move = board.parse_san(san)
except ValueError:
return
if not move: # null move
return
async_to_sync(self.channel_layer.group_send)(
f"game_{self.game_uuid}",
{
"type": "moved",
"san": san,
"colour": self.client_colour,
"time": timezone.now().isoformat(),
},
)
def moved(self, event):
if event["colour"]:
self.update_white_timer(dateparse.parse_datetime(event["time"]))
deadline = self.get_black_deadline().isoformat()
else:
self.update_black_timer(dateparse.parse_datetime(event["time"]))
deadline = self.get_white_deadline().isoformat()
text_data = {
"command": "moved",
"san": event["san"],
"colour": event["colour"],
"deadline": deadline,
}
self.send(text_data=json.dumps(text_data))
self.board.push_san(event["san"])
if event["colour"] == self.client_colour:
self.end_if_gameover()
What's this?
I have posted it as concise and precise as I can, pls ask what part you did not understand, your reply seems like you do not even try to help, and if that is true then you should just not ask, not trying to be rude if that seems like sorry.
In short should i do it like this instead
def move_if_legal(self, san):
if self.board.turn != self.client_colour:
return
try:
move = board.parse_san(san)
except ValueError:
return
if not move: # null move
return
self.board.push(move)
async_to_sync(self.channel_layer.group_send)(
f"game_{self.game_uuid}",
{
"type": "moved",
"san": san,
"colour": self.client_colour,
"time": timezone.now().isoformat(),
},
)
def moved(self, event):
if event["colour"]:
self.update_white_timer(dateparse.parse_datetime(event["time"]))
deadline = self.get_black_deadline().isoformat()
else:
self.update_black_timer(dateparse.parse_datetime(event["time"]))
deadline = self.get_white_deadline().isoformat()
text_data = {
"command": "moved",
"san": event["san"],
"colour": event["colour"],
"deadline": deadline,
}
self.send(text_data=json.dumps(text_data))
if event["colour"] == self.client_colour:
self.end_if_gameover()
else:
self.board.push_san(event["san"])
elems = driver.find_elements_by_xpath("//a[@href]")```
Hello what is it ?
Well... it is telling you what's wrong. find_elements_by_* commands are deprecated, and you should be usingfind_elements() instead
"deprecated" means that for whatever reason they will be removed in some near future
Thank you for your help, I'm testing right now
make tuts on Kubernates
hey
I have an accounting API which I want to access. I have credentials, and made a basic request of an endpoint. All good.
Now I need to learn the syntax for URL requests, how to "link" endpoints, basic query and post activities for APIs.
Anyone care to share recommended resources to get up to speed. Books, video series, Udemy, Edx, etc.
??
Hm, you mean you want to just access that API from python?
The documentation for the specific API is going to be your most important resource. Making simple API calls from Python is pretty simple, just use requests to get or post
I'd recommend httpx over requests 
I'd rather have an ORM
Sorry, what it has to do with ORM?
Object Relational Mapper. Meaning I'd rather deal with objects than JSON, URLs, etc
ORMs usually work with databases, API is not a database
You can convert your json responses to objects
Its simple to make the call, but the data I'm querying is a complex POS system. There are interrelated end points. To get the full picture of the data as it's represented in the POS system in store, you're actually "linking" is the term they use, multiple data sources. All very compled and beyond just calling one endpoint
Thats all good stuff. So, do you have a recommendation for how you learned this?
What do you mean? 🤔
Sorry if I was unclear. I;m asking for resources for learning about APIs
I don't really remember 😅
Fair
If you need to query multiple endpoints to get a full object you need you really have two choices:
- Do it manually
- Create a proxying api, for example, using a graphql library/framework
It would fetch data from that api for you (you have to code it ofc), but for example:
{
getUser(id: 42) { # Could issue call to api/users/42
username,
posts # Could issue call to api/users/42/posts
}
}
It all depends on api you're working with though
Here is the swagger 'docs'
https://api.mobilebytes.com/
sales is composed of tickets which are composed of menu items
Also, here is an issue I was struggling with which I hope learning more about APIs from a book or other educational resource would clarify:
"...their JWT endpoint expects username and password as body field instead of basic auth that the python [module request] generates" [my emphasis]
I struggled with that for three days because I didn't recognize the difference.
permission_classes = [IsAuthenticated]
serializer_class = JobListSerializer
def perform_create(self, serializer):
data = serializer.save(user=self.request.user)
self.request.user.id = data.id
return data```
def post(self, request, *args, **kwargs):
# job_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
# print(job_id)
# job = Job.objects.get(id=job_id)
job = Job.objects.get(user=request.user.id)
try:
checkout_session = stripe.checkout.Session.create(
line_items=[
{
'price_data': {
'currency': 'usd',
'unit_amount': request.data['params']['price']*100,
'product_data': {
'name': request.data['params']['Company_name'],
# 'images': ['https://i.imgur.com/EHyR2nP.png'],
},
},
'quantity': 1,
},
],
metadata={
"job_id": request.user.id.hex
},
mode='payment',
success_url=YOUR_DOMAIN + '/payment/success',
cancel_url=YOUR_DOMAIN + '?canceled=true',
)
except Exception as e:
return str(e)
return Response({"sessionUrl":checkout_session.url})
# return redirect(checkout_session.url)```
can someone tell me how to call pk. after i save the entry in database?
I'm not able to call the pk in request
trying from 4hrs, please need help
Can i use React js in android studio for android development?Also what does a web app mean? Is it something like Website and app or its just a website which can be accessed from mobile?
A mobile app is typically one you download from the app store / play store, a web app is one you access through a web browser (mobile or desktop). React is used for both
Tbh i am looking for all 3 things mobile download + web app i hope it should be possible in react js to do that
from flask import Flask, g
import sqlite3
app = Flask(__name__)
def connect_db():
sql = sqlite3.connect('./passwords.sqlite')
sql.row_factory = sqlite3.Row
return sql
def get_db():
#Check if DB is there
if not hasattr(g, 'sqlite3'):
g.sqlite3_db = connect_db()
return g.sqlite3_db
#close the connection to the database automatically
@app.teardown_appcontext
def close_db(error):
#if global object has a sqlite database then close it. If u leave it open noone can access it and gets lost in memory causing leaks.
if hasattr(g, 'sqlite_db'):
g.sqlite3_db.close()
I have this code to connect my sqlite db to flask web app but when I try to display it out as a table format
it does not work
db = get_db()
result = cursor.execute('SELECT * FROM passwords')
data = result.fetchall()
return render_template("account.html", data=data)
this is the query
<table class = "table table-striped">
<thead>
<tr>
<th scope="col"> Name </th>
<th scope="col"> URL </th>
<th scope="col"> Username </th>
<th scope="col"> Password</th>
</tr>
</thead>
<tbody>
<tr>
{% for entry in data %}
<th scope="row">{{ entry[0] }} </th>
<td>{{ entry[1] }}</td>
<td>{{ entry[2] }}</td>
<td>{{ entry[3] }}</td>
{% endfor %}
</tr>
</tbody>
</table>
this is the table code
How can i add picture 3d (blend) to my webstie with django?
Can someone please tell me how to connect mongoDB to Django ?
can someone help me with flask
Registration form isn't storing data into the database and/or doesn't redirect back to home page to display user
(django) Hello need some advice
class User(models.Model):
# Bunch of fields
class Deck(models.Model):
# Bunch of fields
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
class Card(models.Model):
# Bunch of fields
deck = models.ForeignKey(Deck, on_delete=models.CASCADE, null=True)
running python manage.py makemigrations and then python manage.py migrate make this error to occur:
hey is anyone aware on how to render forms/database like its done in django-admin, but on a users panel
anyone familiar with multi-site deployment with Django? Does this tend to cause difficulties down the road? Alternative is a multi deployment of django code base. I see some issues managing the configuration with a multi-site deployment but a cost benefit
how can I get the input values of a HTML file using Python?
(I need this to also work on Replit)
An example would help clarify what you mean but it sounds like you could search for an xpath with lxml
And I believe that would work on replit if the HTML is a file is part of your repo
Hi I would like to know how do I send files using flask in python.
Im currently making a form that takes image urls and downloads them from the internet.
This is my current code I dont know why it isnt working, can anyone give me any thoughts on why the function isnt working:
@app.route('/', methods = ['GET', 'POST'])
def upload_file():
if request.method == 'POST':
default_value=0
f = request.files['url',default_value]
f.save(secure_filename(f.filename))
return 'file uploaded successfully'
I'm in help channel #help-cake so if someone can help me out just ping me there
wait web can develop by python? i thought just javascipt and php
Yes.
Frontend oriented web can be developed only by JavaScript
Backend oriented web can be developed by.... JavaScript, Java, PHP, C#, Python, Golang, Ruby and e.t.c.
Check what React Native can do
As far as I know it is possible to write code for web app and mobile app parts within same react project. Or at least I thought so
directory.
guys please help
i set the environment varibale for flask on windows
but still getting this here
(django) I made an app users and added custom user model and allauth, turns out i don't even need authentication, how do i remove users app? just delete it? i dont have any models for atleast now so don't know if i would need django admin, so do i remove django admin and auth as well? i think i should just keep it and if that is, should i just not delete custom user model?
Hey
Can you share the file name the Flask app is located in, and the command(s) you used to set the environment variable?
You probably don't need to delete the models. I would just delete the url path to the admin site if you don't want that to be accessible at all
so keep the custom user and remove allauth and sites app?
if anyone familiar with flask_restful
is
from flask_restful import Api,Resource,reqparse
api = Api(app:=Flask(__name__))
class test(Resources):
def get(self):
...
api.add_resource(Users, '/users')
same as
#imports
app = Flask(__name__)
@app.route('\users',method = ['GET'])
def test():
...
except the former one uses REST API
thx for the reply and sorry for my late reply, um the thing is the firefox download dialog gets triggered if js code is executed (which is happing upon clicking on <a> tag element)
this is the website in question
i was thinking that i might need selenium, however i thought maybe python requests lib could handle this aswell
Given that the link launches JavaScript, yes I do think Selenium is likely needed, unless you can reverse engineer the file request with developer tools and bypass the JavaScript.
The accepted answer here may help: https://stackoverflow.com/questions/12146403/disable-firefox-save-as-dialog-selenium
many thanks 🙂
Hey @native tide!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Hmm okay
thanks
django rest framework, testing
so I put this before my TestCase class
token = Token.objects.get(user__username='admin')
client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
but when I run tests for some reason i get 401s, while when i do this in terminal with python interpreter i get expected responses (200, 201, etc.). What am I doing wrong?
Guys, one very small question
What's the best way to ensure that a dynamic task runs only once in celery beat? I'm passing a date and time to this view from the frontend and assigning everything from the minute to the month to the task, but I can't assign the year so the task will repeat once every year right?
If I just set one_off to True will it run only once?
hello I've never made a website before, but I had this idea:
I want to connect my bluetooth headphones to the pc
I don't have bluetooth on my pc
So:
Let's make a website take takes in all of the sound on my pc
Send it to my phone
And my phone sends it my bluthooth headphones
How do I even begin to make this?
how do I center a text right in the middle of the screen
and it's only within its container
Hear all the sound of your PC or laptop on your phone. Use Wifi or USB. Since there's no delay, you can stream your games, movies or music.
You mean a modal that "floats" on top of the page? Easiest way is probably with Bootstrap: https://getbootstrap.com/docs/4.1/components/modal/
heyo does someone know how to correctly set a firefox profile in python selenium webDriver ?
# create ff profile
profile = FirefoxProfile()
#profile.set_preference('browser.download.folderList', 2)
profile.set_preference("browser.download.dir", targetDir)
profile.set_preference("browser.download.manager.showWhenStarting", False)
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/xls;text/csv")
profile.update_preferences()
options = Options()
#options.headless = True
options.profile = profile
driver = webdriver.Firefox(options=options)
i tried the following however got a DeprecationWarning: firefox_profile has been deprecated, please use an Options object profile = FirefoxProfile()
then tried the suggestions in the docu, also didn't work unfortunately 😕
I solved it I’m using Chakra Ui
Is there a way to make rendering pug file in flask app like I can do in NodeJS?
I tried looking for it and the closest thing, which appeared was sucuri which hasn't got linting in VS Code
do you know how I can run my script on a webpage
or will i have to rewrite the script to make it work on a platform like flask
What script?
If you want to pass inputs and outputs between flask and an existing script, you may not need to rewrite much
Oh im sorry i had to go eat lunch
But thank you for the help
I can send you the script amd maybe you could help me figure out what i need to do?
please help, I'm having this error when running the Dockerfile
I want to run it via localhost using manage.py
Should I use different endpoint URLs for GET and PUT? For example if I want an endpoint to list all of some model X, but I also want someone to be able to pass in an id that represents a model's ID in a database, and the backend would set some flag, lets say.. isdisplayed, to False
I don't have anyone to really ask for what would constitute best practices so I thought I'd ask the hivemind
My initial instinct is that I should probably use two completely different URLs, for example
GET users
PUT users/hide (and I can pass in id: 1 or something and handle that)
But there's probably a non-zero chance that best practices suggest that GET users and PUT users is better?
<button type="button" class="aAr9nYtPsG7P2LRzciXc">Follow</button>
how do i find this elemant with selenium as there is no id or name
ping me when reply
thank you. I will try and follow this. I'm worried that I may want to use PUT users/{id} for more than just setting a flag, but then I recall that PUT allows any attribute to be updated huh
So I am responsible for handling what's allowed in the PUT and whatnot then I suppose
Whoa, that's the first time I heard of this. Thank you
I think it's telling you setup.py doesn't exist in the working directory. If it does, maybe an issue of file permissions?
Look into xpaths. You can approach it various ways but //button will get you any buttons in general and then you can use the class and/or text to specify
would it be //button[@class='aAr9nYtPsG7P2LRzciXc']?
That's one way that should work, yes
If there is more than one button with that class you can either get the first one, or get them all
Or specify based on a parent tag
how can i do this?
it's in the root directory, maybe on my configuration? here is the configuration of scripts/ci-runner.Dockerfile:
should I add something on that configuration?
Is it possible for python to find out what website is open on your pc?
everything is possible, but it would PITA (Pain In The Ass) level of task.
Because you are wishing for action that is often performed by virsuses and other mailware
oh
but do you know how to do it?
among ways that aren't PITA
you can track your own web site that is opened
by making some JavaScript hooks
Also as not PITA would be to have it in Chrome Extension functionality, it should be having access to this data with right permissions
ohk
@inland oak isnt it easier to just see which tabs are open
and then if lets say instagram.com is open it will basically play a sound
I was learning about flask API
in my main directory, why did this pop up
Is it safe to delete
.vs and database.db
This is all that I've imported
You probably shouldn’t delete database.db. That’s the file that acts as the database.
how to block all websites except 2 in python?
you're gonna have to explain a little more in context
basically im making a program to help me focus
currently i have made it so that if i open some games it airhorns and sends a notification
but.. i also wanna do the same to all websites except for google drive and gmail
it is ok if whenever i open a website other than that, it gets detected then my program acts on it
From what I understand, you want your Python program to detect what website you're on and act on it in the background?
the task can be fulfilled in the nice way only in Javascript
while it is still possible in python, it is by magnitude harder
ok
bingo
how can i do that?
https://developer.chrome.com/docs/extensions/mv3/getstarted/
Get started with manifest 3 chrome extensions
write in its settings to access the necessary Chrome API that allows to check current urls
https://developer.chrome.com/docs/extensions/reference/
one of next permissions should be containing the access to urls
"permissions": [
"webRequest",
"tabs",
"http://*/",
"https://*/"
],
then do you deed with the acquired data
ok
where do i write the settings of the extensions
im not sure i get you
do you have sample code or something?
https://developer.chrome.com/docs/extensions/mv3/getstarted/ read get started tutorials
or find examples of the code in google
ok...........
although official docs are better
but why do i need to make an extension tho
because extension has access to browser currently opened urls
extension is in browser application, it has access to do the job you wish
ok.........
now i gave the chrome api access to check tabs n stuff
now how can i integrate that with python?
@inland oak
Sorry, can't resist writing meme as a joke-answer
Chrome extension is just another frontend application, treat it like that, (like already rendered web page)
if you wish its integration with backend python application...
request in it endpoints of your python backend application
that accepts and outputs data in JSON data
So... like, write in JavaScript, request to query your python backend, https://yourpython.com/allowed_urls_to_visit
and get answer like
[
"blabla",
"blabla2": { "tratatata": 123 }
]
to acquire list of allowed-white listed urls or any other data
in similar requests you can input data to python
BRUHHHHHHHHHHHHHHHHHHHH
dude my mind rn
can somebody help me to find the code for this problem , please ..
!rule 8
8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.
this is not for exam . this is my interview question
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
A guide for how to ask good questions in our community.
We don't help people to find code for a problem. If you did something and you're stuck, we are happy to help.
pls get me out of this server
just leave
Hiii, Can anyone please guide me in understanding CSS box model
hi guys , what are the most commonly used python framework that companies use for their backend ? is it django or fast-api ? or what kind of way do most of them do to achieve real-time app ? do they all use django-websocket if they use django for their REST API ? or what's the other options? I'm newbie here
I need some understanding on alignment of boxes, Tutorials and videos weren't able to help me
Look into Flexbox:
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox
The Flexible Box Module, usually referred to as flexbox, was designed as a one-dimensional layout model, and as a method that could offer space distribution between items in an interface and powerful alignment capabilities. This article gives an outline of the main features of flexbox, which we will be exploring in more detail in the rest of the...
hi guys I was interested, if you include google analytics to website, what kind of notice you have to write (except for this site uses cookies, OK)
Is there some template document/text for that?
Hello, I am making a project site on flask, in which students can post complaints about their academic problem on the site and the teacher can view every students complaints and can also give response(or feedback to any complaints) on teacher's dashboard. Students and teacher have their own specific dashboard( admin panel) . The problem is that after a teacher gives the feedback or response to any complaint, I want that the complaint along with the feedback should be shown to student dashboard.(html template).
How is it possible?
I think its all about id's but not sure
I would recommend you to show your code in a help channel #❓|how-to-get-help
how do u leave?
right click the server
If you want to ping me I can take a look
ok
JS or TS?
It depends
If you're already familiar with js and build tools i'd say ts
How to make it so that there is a dot before the capital letter /::marker
I'd try using unordered list if you can
Hey guys is there someone who could help with django test system ? if possible in private bcs my english sucks and i have sometimes trouble to explain what i rly need
I could help but i'd recommend using pytest instead 
i can't change sadly its for my school and i have to learn how to use the TDD method with django test system
I think you could ask your teacher if you can use pytest since most developers use it instead
someone already asked he's one of these annoying teacher yk
It's still testing, pytest is just more modern and is easier to work with
What kind of help do you need then?
i have to test on my view ,models and urls but i don't know what to test and how to do it
like he said i have to respect the red greed refactor thing but im lost
i can try to show you what i've done that far but it's not much
Okay!
ill take a look if you post it
Well I'm at school.
ah ok
Yeah,
Anyone have experience with the traceback error NameError: name '_mysql' is not defined when importing flask_mysqldb?
I keep getting the above error, even when flask-mysqldb is clearly installed when i run pip3 list
Here's a snippet of the code for reference ```py
from flask import Flask, render_template, request, redirect, url_for, session
from flask_mysqldb import MySQL
import MySQLdb.cursors
import re
app = Flask(name)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'password'
app.config['MYSQL_DB'] = 'login'```
Can you share the full traceback to the error?
Also, what's MySQLdb.cursors? Is it from the mysql package, or is it something you created?
Hi! I would like to display a json file like this
https://raw.githubusercontent.com/bleach86/Tuxchat/main/settings.json
where would I look for how to do that
Yes, that's a JSON file. What are you trying to do?
display the contents of a json file like in that link. I figured it out
from what I heard its Flask and Django for API many developers are leaning towards FastApi but if you already know django drf why bother? if it can handle and accomplish the same job.
hey guys,
do you think that a rubyonrails developer should switch to python webdevelopment
like flask django or something like that
hello, I got a 255-length alphanumeric token from my dev lead. I was told to use this on my headers as authorization for my requests. Which type of authorization is this?
mmh like a cookie?
as far as I know, Ruby on Rails and Django are more or less the same thing
so... what would be the point
Django could be more popular/easier to find work with in his region
Popularity wise ruby and rails are declining a bit right now. So you could switch to python for a better ecosystem maybe.
I have built a react project now I want to edit or add content from a dashboard rather than every time tweaking the code. Before that, I build the project with the Django backend and bootstrap with the help of the Django admin panel I used to add content now when I moved the project to react I have shifted the Django backend into a rest API. can someone please share some resources or point out to me in internet
Hello, is it possible to provide auth from another framework and authorize it on Django? I know there is OAuth, but I mean can I do the authentication on another framework like express, laravel, etc... and the tokens get authorized by Django.
yes
JWT tokens as a choice should work fine
procedure
- Client AUTHed in your another framework, your framework has SECRET_KEY_1 and sent a sticky cookie with JWT stuff to identify user
- Your user goes to Django Framework, with same SECRET_KEY_1, you validate sticky JWT token, success
it need some configurations on settings.py on the default authentication or similar right?
Okay, Thanks!
you will be expected to read the cookie containing JWT thing from cookies of the incoming request
https://stackoverflow.com/questions/5113660/how-to-set-or-get-a-cookie-value-in-django
something like that
(heavily outdated page, but probably stull working example)
will check that! appreciate your help
Hey guys, I'm currently working on a beginner django project, trying to build a basic forum. Since I'm a bit stuck I hope you can maybe help me out. I want to automatically have a new html page with some content on it created when a button is clicked. Do you have an idea how to do this?
You should go through a django tutorial on how to create something like a blog. That will teach you this.
djangogirls tutorial is very good
hey yall wanted to know if anyone knew how to use regular expressions for a hashtag word in between non hashtag words, for example:```
I love #learning. It's so fun #selflearner #selfstarter #learn
What I am trying to do is keep the word learning but get rid of the other hashtags at the end
You can do this with JS pretty easily. I don't know if that's the best way though.
Hellow bros, i little question
django told me that there is an error if i dont pass the id param
just bar main
how to avoid it? Make both posssible bare and main with arguments
@winter mirage
So I am making a simple Flask app that displays the content of a json file. how would I go about making the background of my page darker and add syntax highlighting to the json?
<html>
<body>
<pre>{{ content }}</pre>
</body>
</html>
this is my template file if that helps
I'm worthless when it comes to web oof
Anyone know what dumptext.com is?
Or was?
Was this site used to dump code at one point?
Anyone heard of this site before?
@rocky cradle I mean, probably not?
The wiki site look better in desktop mode on my phone actually
Yeah but I guess that it should be improved for mobile mode
I have problem with three.js
driver = webdriver.Chrome(service=Service(ChromeDriverManager(log_level=0).install()), options=options)
WebDriver.init() got an unexpected keyword argument 'service'
try .models not models
can you send more code of where you are trying to import it too and where its importing from?
whats the code inside the models file
one moment
try importing the database before importing the user
so change their order in the list
are you able to post the full tracebacks?
ah i see whats wrong, your folder structure isnt setup correctly
How do I fix??
https://iq-inc.com/importerror-attempted-relative-import/
this has 2 solutions, the first is quick and dirty and i dont suggest following, the second solution is much better and involves essentially creating another folder to put the different views, auth, signup, etc in
I have an init
@thin marten
I still need help i TRIED.
leave init where it is and and add a new folder titled "pages" or something then put auth, models and views in it. youll have to restructure some imports in the code for the new locations but from there you should be able to from pages.models import User
it wont be with these names specifically but the file structure should look like this inside the "website" folder
They are in a folder.
send a picture of the file structure
hold on
foo = "flask web app" in your structure
you may want to rename the folder from views since it will likely cause namespace conflicts (in the example i put)
i dont know what else to try from here. if your following the video i think you are id double check the file structure and make sure its the same as his and other than that im not sure. sorry
@thin marten
nice, what was the issue?
I didn’t have a database.txt
For it to save the stuff hence the DB issue
@thin marten
ah
I’m gonna show my teachers tomorrow
Lol jwts are bad😁😂🤔
You should just use simple random tokens for authentication
woah? They are the best for microsrvices
I will not 😠
How am I going to verify your random tokens in other microservices
and JWT transmit me additional data with them to tell user rights, i wish to have it
I meant using jwts itself as an api token is bad
sticky cookie
??
once user authes in our auth api
we send in reply Sticky Cookie with flag to forbid javascript access
the cookie is sent automaticlaly back with every request from the user to the same domain
Alright, what's in the cookie?
we just read his side car to the request
additional payload to every request ;b with expiring feature
capable to carry up to 4k of information
4 kilo bytes
we send JWTs in Cookies
Hmm but why
we store JWTs in Cookies
Is it to be stateless?
Because it is convinient and better secure! Frontend code has no access to Cookies with javascript forbidden state flag in them
Imo statelessness is impossible when you handle authentication
All auth stuff of backend is obscrured away from frontend 😉
No, I meant to ask why send jwts in cookies lol, not why you send sticky cookies
You could send simple random tokens instead
how do I validate random tokens
and how to i transmit necessary additional info inside of them
that tells me the info of user
how the fuck do I validate it is the same user at all, how do I identify him if he came to me with random token
JWT can tell me exactly which user it is
with adding any additional info about him, email, user id in database or anything i want
Store the token in a table??🤔
WHY!?!?
it is additional request to SQL Database
it is uneffefficient!
and I would need validate every time from database!!!!
You will get the current user from the database anyways right? Why not make a join
JWT token can be validated without database, even in other microservice
JWT token can be used to AUTH ACROSS MULTIPLE MICROSERVICES WITHOUT VERIFICATIONS FROM DATABASE!
no additional requests
we auth once, one request to SQL database at the beginning and that's it
Okay, but this involves tradeoffs too
You cannot invalidate tokens at once
You'll need a blacklist
I can put inside as much invalidating things as I wish
Which makes the whole flow stateful
I can put time expiring into it
I can put into it email and any other user info
anything that I want to invalidate it
time expiring should be enough as it is working across microservices to invalidate them
Let's say you have a jwt with an user I'd as payload. It expires in 5mins. When the user is deleted from the database, the jwt has stale payload
sure, that's a bit of trade off, but usually user requests to delete himself, then I could delete his cookie during the request, or during his next auth operation
or since he was deleted... if he would try to make operation that he is not able to do any longer, he can just encounter 403 forbidden access ;b
the service will work fine
This doesn't necessarily need jwts, you could do the same thing without the tradeoffs mentioned above using hmacs
It's in the article I linked above
Same principle applies
alright though, this was a fun debate/ discussion lol
Tbh they're still vulnerable 🤔 during an xss attack attacker still can send requests to the service and browser would attack cookies to them.
I'd say it's the same level of security as storing jwt in memory and adding a random string in a cookie and it's has in jwt
In both cases attacker could use jwt in client's behalf but it can't be stolen or can't be used outside of user's browser
@twilit needle @inland oak
https://cheatsheetseries.owasp.org/cheatsheets/JSON_Web_Token_for_Java_Cheat_Sheet.html (Not only for java)
Website with the collection of all the cheat sheets of the project.
in django while registering a new user how do i check if that username/email is already registered or not
User.objects.filter(Q(username="Username") | Q(email="YourEmail))
or you could do separate queries for username and email too
ahh lemme try
This query would select all users who's username or email matches
essentially where username = 'Username' or email = 'YourEmail'
ah okay
what does this Q stands for? do i need to import it or something
alright thanks
@serene prawn I tried to register with the same username and got this
this is my views.py file
username="username", you have to check with username that was send to your form
this is what was send to me
This is your form, could you show me how you're trying to create your user?
Or just more code 
alright
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib import messages
from django.db.models import Q
import re
# Create your views here.
def register(request):
if request.method == 'POST':
username = request.POST['username'].lower()
pass1 = request.POST['pass1']
pass2 = request.POST['pass2']
email = request.POST['email']
fname = request.POST['fname']
lname = request.POST['lname']
#Sanitizing inputs
if len(username) > 15 or len(username) < 8:
messages.warning(request, "Username length must be between 8 to 15 characters.")
return redirect("/register")
if not username.isalnum():
messages.warning(request, "Username must be alphanumeric.")
return redirect("/register")
if User.objects.filter(Q(username="username")):
messages.warning(request, "Username already exists.")
return redirect("/register")
if pass1 != pass2:
messages.warning(request, "Passwords don't match.")
return redirect("/register")
regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
if not (re.fullmatch(regex, email)):
messages.error(request, "Enter correct email.")
return redirect("/register")
#Create User
myuser = User.objects.create_user(username, email, pass1)
myuser.fname = fname
myuser.lname = lname
myuser.save()
#Success Message
messages.success(request, "Your account has been successfully created.")
return render(request, "login.html")
else:
return render(request, "register.html")```
this views.py and register.html
I don't need the form 🙂
lol i will just delete it, coz its taking too much space
You could just do
if User.objects.filter(username=username)):
messages.warning(request, "Username already exists.")
return redirect("/register")
instead of User.objects.filter(Q(username="username"))
lemme try that out real quick
this worked
thankss a lot mate
I am looking for Python Website and application Jobs with Django, Flask, Fast API.
it even worked for email, thanks a lot doctor
What's the difference between % and %- in Jinja?
% is the default one for programming actions
%- does same actions, but removes spaces at the left, -% does the same but removing spaces at the right
@inland oak You store both access and refresh tokens in cookies?
Let's assume yes.
(Truthfully so far my access and refresh token were the one token)
They're still vulnerable to XSS attack (it's not like you could really do something about it) 🙂
I guess all you can do is minimize the probability of xss
Mainly cleaning everything you're displaying on your page, frameworks usually do that for you
Essentially storing it in cookie prevents attacker from stealing it but it still can be used in client's browser as i mentioned
my web site is not having user written content, so xss risk is highly minimized I think
it could happen only if user has something like usafe plugins installed
Yep
Ah okay, makes sense.
I have one view (ModelViewSet) which is for shop owner and for normal user of shop who wants buy smth. Shop owner has access to all methods, he gets full data about shop on GET request. Normal user has access only to read and he can get only selected data, not all data about shop. What is better solution?
- One view, 2 serializer for this view (get_serializer_class) + override get_queryset and get_object methods where I will filter it (because when owner of shop want to get all data about shop I filtering it
owner=userand when normal user wants some data about shop using same view I don't want to filter it) - Two other views with 2 other serializers - one for shop owner and one for normal user
I have many views with situation like this, so using first idea I would have much code duplicate (bcs of overriding getqueryset i getobject)
What is your error?
yo guys, can i have some help whit javascript?
why this don't work? js for (key of setup_methods) { var e = document.createElement("button"); div_input.append(e); e.onclick = key["method"]; e.innerHTML = key["nome"]; }this code should add some buttons on a div but nothing happen and i get no errors in the console.
Hey guys I am new django and wanted to ask is it compulsory to have a static folder in your django project?
for (const key of setup_methods) {
if you have static files, yes
I want to build a simple web page where we can upload any particular Image.
Okay
You can use fask or django
Come on VC
No you need to have media folder
I am using Django
what's a media folder😅
It holds image uploads
Okay now I get it
so i was watching a tutorial and made a project that was there in the tutorial and after hosting i saw this when i was sharing the link to one of my friends how is this possible that dennis ivy (the youtuber btw) name is shown here?
what code?
A guide for how to ask good questions in our community.
copied a code from a youtuber to study and learn deployed it in heroku and its showing this....text ...the name of the youtuber is Denis Ivy
its a django project so i dont know what code do you want
The page that the link goes to has meta information like author, link, etc. and it is pulled from there when the link is shared.
Look at open graph to setup your page to have meta information like this. It has to do with SEO if that helps.
thank you
guys my page keep reloading while i am streaming by openCV anyone know any solution to stop this reload?
Hello, i'm doing an app with django backend and nextjs fronetend, i was able to finish my authentication system using jwt http only cookies. Now my question is, what would be the right approach to obtain and update the user information?
i have a refresh and access token on the browser plus an endpoint /verify in my database to check the token
What do you mean by update user information?
I mean that, in addition, they have objects (if it were an application like instagram they would have posts, and comments, etc) and they must be able to upload and update this information
would be information linked to the user
I mean you just update the info like you normally would, sending a mutation/call to the API to update the user information with whatever data you send, but you use the cookie to authenticate whatever you need to in order to allow for it.
Using django-jwt?
and REST or graphql?
So when you signup, you send a request to the api with the information.
yes
Same thing when you update information.
Just send the data from the form to your API.
Does that answer your question? I'm not sure if that's what you were asking.
I assume the cookie has user data in it.
I use django-jwt and it sort of handles all of that.
ok thanksss
hi guys, i have a problem with running multiple django website with apache. first one work fine but second i get wsgi error Timeout when reading response headers from daemon process
I bet simple-jwt has a function to handle it for you.
In django-jwt/grapehene, I just have the login_required decorator that calls the function to validate the cookie.
And if it's valid, then it uses info.context.user or something to grab the data.
I don't know exactly where it holds that.
thanks, i will read the documentation to to look for some functions or clarify my doubts
Can you use bootstrap with flask?
hey guys so i have a discord bot and i wanted to make a website that i could tweak different settings for the bot from. I have used flask a bit in the past and i wanted to know if there was a way to asynchronously start the discord bot and the flask app main threads so that they could communicate with each other
i've had some trouble with doing that, so can someone point me in the right direction or tell me if i'm even going about it the right way?
!pypi quart-discord
start the discord bot and the flask app main threads
There's a thing: You don't
Depending on what settings you want to tweak they could just use the same database
I mean they should use the same database
okay, that makes sense, can you point me to an article or video?
!pypi quart-discord
You don't need quart for that 🤨
yea ik
discord.py would work
yes, im to do that exactly
discord py doesn’t make websites
yeah, but how do i make it send data to the backend client?
They should be separate applications
mhmm
@dull isle You can connect flask app and discord bot to the same database 
okay, do you have a database reccomendation?
Postgres is good
Postgres
alright cool!
Personally postgres + sqlalchemy as an orm
ill look into that, thanks, y'all
i dont know enough about backend to understand what you mean 😅
It's a popular python orm, you'd probably use it with flask
okay, cool, ill look that up too
unrelated question but do you would prisma is better than sql alchemy or could provide better functionality. I think there is a Python version for it
They're different things
mhmm
prisma itself is not a relational database
ik
sqlalchemy is working with sql databases (sqlite, postgres, mysql, etc)
Yep
Oh, actually, wait 🤔
?
I actually meant cassandra 😅 It's a db that discord uses
Prisma should support sql databases
yeah I was confused because I was watching a video. It said it works with sql databases
From the first glance - i don't really like prisma:
posts = await client.post.find_many(
where={
'OR': [
{'title': {'contains': 'prisma'}},
{'content': {'contains': 'prisma'}},
]
}
)
# vs
select(Post).filter(or_(Post.title.contains("prisma"), Post.content.contains("prisma")))
Just a personal thing i guess
Understandable
sqlalchemy supports a lot of weird cases, you could configure a lot of things 
Hey guys!
https://paste.pythondiscord.com/upujowafud.kotlin
https://paste.pythondiscord.com/imamuzawit.xml
https://paste.pythondiscord.com/uxazexuvug.py
for some reason I keep on getting user is not defined
I have a login method and do login(user)
however on the HTML it keeps saying user is not defined and I am really confused
Anyone here experienced with flask? My current file structure is something like this:
app/
- templates/
- test.html
- views/
- main_view.py
- __init__.py
main.py```
However when i try to load a template `test.html` from main_view.py it returns a TemplateNotFoundException
I would really appreciate if someone could help me on this, been stuck for a bit haha
By convention templates are located directly in templates dir, yours is app/templates, you could pass a template_folder parameter into Flask
e.g. Flask(template_folder="app/templates")
alr
The prisma python client is not official and doesnt seem to be stable/ maintained
I've Integrated a websited with google sheeets but now it is showing unusual behavour can any one please help me in finding and fixing the bug
Hey, im someone whos weak at math and lack problem solving skills, but would still like to pursue college. I thought that switchijg from CS to IT would be more beneficial to me despite CS being more prominent since I would prefer to be in the front-end rather than the back. Would considering switchijg my major to IT be a lot more better in my situation?
lets start with me telling we have no idea what is your country and type of education in it
as a second, this is probably question for #career-advice channel, it is often discussed there
U.S
Inside paramters of both the function u only have to pass request not HttpResponse
ok
like the login method
N yeah in 2nd func (i.e login) why did u pass HttpRequest)
request
Is enough
ok but it gives error
def login (request):
return render(request,pages/index.html)
Show ur code
- Error
what's the difference between flask-login, flask-admin, and flask-security?
{% if guild.icon_url is not none %}
<img src="{{guild.icon_url}}" class="{{guild.class_color}}" />
{% else %}
<img src="https://discordapp.com/assets/322c936a8c8be1b803cd94861bdfa868.png" class="{{guild.class_color}}"/>
{% endif %}
</a>
<br />
{{ guild.name }}
it dosent load the image in else. Any help?
it dosent load
the image exists tho. U can copy and paste it in ur browser
use .url instead of _url dude
It's always use of . When we fetch remember that
N it will work
that one works fine. the problem is in line 4
Kinda impossible dude
See ur if statement
change it to
guild.icon.url
Not guild.icone_url
icon.url wont work dude
i just did
no
it is saying guild object has no attribute icon
the syntax is icon_url
Show me ur models
I'm using a module called quart_discord
jinga usually does that
None- N should be capitalized
yeah
Ik solution of this
To check if
Just write
if guild.icon_url
Remove is not none
It itself checks
ok i am trying
Smarty
k

<section class="cards">
{% for guild in guilds %}
<div class="card">
<a href="/dashboard/{{guild.id}}">
{% if guild.icon_url %}
<img src="{{guild.icon_url}}" class="{{guild.class_color}}" />
{% else %}
<img src="https://discordapp.com/assets/322c936a8c8be1b803cd94861bdfa868.png" class="{{guild.class_color}}"/>
{% endif %}
dosent throw error
but it is still the same
I dont use jinja2 that much, the last time I did was to do server side template rendering
i just started learning
not any error but the else statement in my code dosen't work
Could you do a quick test
print(guild.icon_url)
sure
ok just a sec
Before you render the template
@app.route("/dashboard")
async def dashboard():
if not await discord.authorized:
return redirect(url_for("login"))
guild_count = await ipc_client.request("get_guild_count")
guild_ids = await ipc_client.request("get_guild_ids")
user_guilds = await discord.fetch_guilds()
guilds = []
i dont have guild obj in the py file
@app.route("/dashboard")
async def dashboard():
if not await discord.authorized:
return redirect(url_for("login"))
guild_count = await ipc_client.request("get_guild_count")
guild_ids = await ipc_client.request("get_guild_ids")
user_guilds = await discord.fetch_guilds()
guilds = []
for guild in user_guilds:
if guild.permissions.administrator:
guild.class_color = "green-border" if guild.id in guild_ids else "red-border"
guilds.append(guild)
guilds.sort(key = lambda x: x.class_color == "red-border")
name = (await discord.fetch_user()).name
return await render_template("dashboard.html", guild_count = guild_count, guilds = guilds, username=name)
here it is
i use ipc to connect
with my bot
Could you please explain further?
If your else block is not rendering it means that every guild has its icon url
Every discord guild has one, even if you dont set one, discord creates a default icon everytime, if I'm not wrong
when tehe guild has noicon, it is defaulted to "none"
if no custom icon is setup, it sets the icon url to none. If it is accessed by api, it is none
but u can see the icon in ur client
Could you print the guilds you have to the console and check the icon URLs for each?
okay just a sec
Just do
for guild in user_guilds:
print(guild.icon_url)
yeah it prints
So every guild has its icon url set
but dosent count guilds with no icon_url
??? What do you mean
Well no, they are icons too, right?
But I dont see any None in the terminal
it dosent print none idk why
but it dosent count them too
How are you sure
i clicked on each of the icons
to check
none of them are default icon url
i even counted
only them dont get counted
Well, maybe in those guilds you dont have administrator permissions
So you dont collect them
i'm owner in them
Hmm, what is rendered in the browser?
here is the code
ok
icon of the guild with no icon_url
but it dosent render
meaning it gets added but not rendered
html problem then ig
So.. the else block executes properly?
yes
i tried to remove guild.class_color
it still dosent work
<img src="https://discordapp.com/assets/322c936a8c8be1b803cd94861bdfa868.png"/>
<img src="https://discordapp.com/assets/322c936a8c8be1b803cd94861bdfa868.png" />
Try this?
Try pasting in some other url
ok
i tried adding another img. Dosent wok as well
Then it might be an issue with your markup
But as I said I haven't used jinja a lot
So I cannot help you further, maybe someone else will!
ok thanks for your time :)
So this works when im using python terminal but it wont actaully show the country when i try to put it in my flask_app.py
@app.route('/covid/information')
def covid_info():
conn = sqlite3.connect('data/covid.db')
cur = conn.cursor()
row = cur.execute("SELECT * FROM countries WHERE Country='Chad'")
row = row.fetchall()
location = row[0][0]
return location```
@stark tartan 😆
File "<stdin>", line 1
.
^
SyntaxError: invalid syntax
What is that
a joke to your msg with . that you deleted
or I am just too nervous due to my product coming to production launch. That could be too.
Why are you nervous
I am not sure if I anticipated everything. Well, everything is impossible to anticipate.
the product is made out of microservice architecture, in kubernetes cluster, with at least 4 different applications, backend / frontend and e.t.c.
everything is covered with unit and integration testing, everything is automated with gitlab CI pipeline, I made in 5 layers coverage of infrastructure with monitoring / logging systems
But did I consider everything? Is it ready to have reliability 99%+ up time?
will I be able to react in time to scale the infrastructure?
Oh! I remembered. I need to setup auto alerts!!!!!!
Ohh my god 🙏
I just learn docker 😅
I was just responsible for every part of the product alone. And I am a bit nervous if I was able to anticipate everything
Is this the company project
yeah
the thing is. microcompany / startup
So I am reponsible for everything of the tech nature
I have no one to blame except me for any software related fuck ups 😉
I guess reading SRE book is kind of like reading a book of all possible illnesses by the doctor
I start to see posibility where the service could have complete breakdown in different scenarios
or I just should go to drink beer 🍺 to calm down
surprisingly it is very hard to make sure that web service has 99%+ uptime/reliability
so many things can go wrong
and would you be able to notice them, or it would go wrong and you did not even notice? That's the problem
highly efficient monitoring / logging is required just to see it, the question raises though, will it be enough
@inland oak Don’t think you should really worry or get too stressed over this. Bugs, issues or unnoticed problems will always be there. In my case every project we take we have dozens of devs, UX, QA testers and still there are bugs. Sure you can do things to avoid issues like this, but it doesn’t matter if your a lone wolf or working in a large team. The system will never be perfect, for everyone.
Yes, I know that.
But still.... I question myself I did not miss some highly important best practice / possible moment that I should have done?
I guess I am just mentally checking every part of the product if I did not forget something INCREDIBLY simple and stupid
Something like... a hole in security that can be easily exploited 😉
Or if I made sure to enable prod level scaling of the every part of application in every part of the product to handle real workflow
Seems you are thinking a lot into the future.
Anyway, the list in the mind I think is fully checked.
The only possible issues I find... I did not setup auto alerts yet, and I did not install higher storage for logging database.
Besides that the only thing is left to choose the server resources to run the production, having it approved and to make performance testing that it works well
and I should be ready to go
You generally don’t worry about scaling or performance until it becomes an issue. Optimising for what might be needed in the future now is always a bad idea.
oh believe me, it should be at least dumb checked in the beginning.
Gunicorn by default is locked to run in just one CPU, regardless of available CPUs at server
if something like that would have been missed, it would be disaster 😉
Depends on the amount of workers 
yeah, and default is one worker
Workers also can handle multiple requests if you use something like gevent worker class
Like I said worry about performance when it matters. If it’s that critical or important before your app even hits production, then tell your company you need additional resources in order to achieve what you are trying to do. And that would mean consulting or hiring those who know about this.
I think application should be async in order for that to work one
🤔 Not really
really?
Your app should be to handle simultaneous connections despite being sync
well, if there are at least several gunicorn workers, it would handle
I made sure to have a test with quering endpoint multiple times
including quering some simple endpoint with sleep(1)
My app was able to handle simultaneous requests using single gevent worker 🤔
I was sending a request to an api and receiving a callback at the same time
Default worker just fails to handle second request as expected
I mean... yes gunicorn worker handles multiple requests even if he is one
but if request contains time sleep(1)
it will wait 1 second before going to finish next request
sleep is not cpu bound though 🤔
Are you implying that gevent would just put requests into a queue?
if it is using sync function like time.sleep, highly likely yes
if uses async sleep, then perhaps not
It should handle them concurrently though, let me check 😅
time.sleep is sync, it should prevent concurrency
Again, how was i able to receive a callback with gevent then? 🙂
First request won't finish until callback is done
well, I can't see you code to know what sync stuff you have
regardless if you have it or not, the first request would finish in time, because... the worker would be just locked to process it in sync way for you
the trouble would be for second-third and e.t.c. request made in parallel
Not a lot of sync stuff, mainly database and http calls 😉
I mean, i essentially have two requests running at the same time:
User makes call to Django, it makes call to an API
API to process this requests sends a callback to Django, we have 2 simultaneous requests
import asyncio
import aiohttp # pip install aiohttp aiodns
import pytest
import time
pytestmark = pytest.mark.asyncio
async def test_django_with_sleeping():
async def pinging(
number: int
) -> dict:
start = time.time()
url = f"https://my_url.com/worker/ping_with_sleeping?format=json"
print(f"func=install, type=started, number={number}, time={start}, url={url}")
async with aiohttp.ClientSession() as session:
resp = await session.post(url=url, data={"password": "password_for_test"})
data = await resp.json()
end = time.time()
print(f"func=install, type=finished, number={number}, time={end}, delta={end - start}, data={data}")
return data
results = await asyncio.gather(*[pinging(number=number) for number in range(80)], return_exceptions=True)
print(f"finished, results={results}")
i like async because it allows me to query same resource in hundred amount of times while using just one CPU
quite efficient to test application 😉
Users request can't be done until django is done processing second request(callback)
Try locust
xD, too much for me at the moment
from locust import HttpUser, task
class HelloWorldUser(HttpUser):
@task
def hello_world(self):
self.client.get("/hello")
self.client.get("/world")
😃
I am having a bottleneck in the main... part, which is resolved through Celery to distribute the workload across multiple servers
I tested and knowing for sure the limits of the bottleneck
What kind of workload?
dropped to DM 😉
If anyone can help, I would appreciate that!
+1
what's the difference between flask-login, flask-admin, and flask-security?
Are any of you folks using remote development? What does your setup look like?
rarely. vscode has remote ssh plugin
but using it usually a really bad practice for me
Why?
so i don't do it
because code is supposed to be developed locally in my environemnt, submitted to git cloud repository
and with CI/CD pipeline automatically deployed to server
coding in remote environment is bad as bad it is to code in production/staging directly
it means I did not do proper job to setup development environment and development pipeline
I hear that.
But there are some benefits such as taking advantage of “unlimited” storage and better GPU cards etc
I mean... I am having dev PC as Linux, it is not different in capabilities to servers in my case
anyone familar with leaflet/folium know how i would rotate a custom icon?
Hello when i upload files from form with
fs = FileSystemStorage(location="/media")
fs.save("filename", request.FILES["file"])
It gives Errno 13 Permission denied
i have
MEDIA_URL = os.path.join(BASE_DIR, "media")
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
in settings.py
i wrote
Alias /media /var/www/TheMPDB/media
<Directory /var/www/TheMPDB/media>
Require all granted
</Directory>
to my apache config
perhaps you have chmod permissions broken
try chmod 777 -r /path/to/linux/folder/with/media/static/files
it permits everything 😉
thanks i fixed
It's really chown www -r /path/to/static
someone know how can i see if page is doing playing sound in selenium?
I've never done it and it doesn't look simple, but multiple StackExchange answers come up if you search
It will not fix all types of related problems to it.
For example your regular user, root or regularuser. After chowing, and launching default nginx, u will still face the related to it errors, because it launches as nginx user by default
Whats the difference between a web framework and a web server?
A web server is an application that provides the web pages to clients. When you put a URL in a browser, you're pointing your browser to a specific web server. Nginx and Apache are web servers
A web framework is a library that helps developers build web pages. Django and Flask are web frameworks
All web pages run through web servers but not all are built with web frameworks. A web framework needs to run on a webserver to be accessible
So I can run a web framework with a web server if my app needs to?
Yes, if you have an app with a web framework you must have some form of web server to run it, even if it's just a built in development server like Flask has
Got it, thank you
Good day
does someone here got an idea regarding flask restful api with swagger 3.0? im currently encounter an error with null value
this is my request body
{
"Target": [
{"_id": 1, "user_score": null}
]
}
This is the error
{
"detail": "{'Target': [{'_id': 1, 'user_score': None}]} is not valid under any of the given schemas",
"status": 400,
"title": "Bad Request",
"type": "about:blank"
}
hello everyone , I am having a half day today, I have some work to do.
how can i replace �� or unicode characters on some websites? or i can copy the text from them but can i put them somewhere and have it replaced?
You're working on a web application for automating ads on Facebook and Instagram. The manager has informed you that following user feedback, you need to add a new section to the app to view your weekly campaign performance. The section should allow a user to select a time period, a campaign, and display metrics for that campaign.
Metrics are: impressions, coverage, clicks, cost-per-click, clickthrough rate.
The user must also download this information as a CSV.
Propose an implementation plan for this new section.
In your reply, mention the following:
- How many new pages would you make for this section?
- What existing pages would you modify (if necessary)?
- How many new endpoints would you implement in BE for this section? What would be the functionality of each proposed endpoint?
- What database would you use (relational vs. others)?
- Other details that you consider relevant
Is anyone able to help me with this?
could some one suggest me where to start django from ??
any resources if you could suggest to work my way through!
http://www.obeythetestinggoat.com/ is ostensibly about TDD, but it's actually a really good walkthrough to make a "real-world" django app
anyone familiar with datatables can tell why my classname isn't working?
$(document).ready(function () {
$('#data').DataTable({
ajax: '/api/data',
columnDefs: [
{ className: "my_class", targets: "_all" },
{ className: "my_second_class", targets: 1 }
],
columns: [
{data: 'name'},
{data: 'age', searchable: false},
{data: 'address', orderable: false, searchable: false},
{data: 'phone', orderable: false, searchable: false},
{data: 'email'}
]
});
});
</script>```
Dennis Ivy, Corey Schafers and official Django Documentation
thanks mate
Can anyone guide me I just want to create a webpage like this with Django -
That there is just html and css
you can use Django and it’s Jinja template engine, then serve the template to an endpoint
or url
I basically want to take an Image upload save it in a folder and do some stuff with that image. Completely new to Django so I thought I should give it a try using Django
as I said, what you want to do is just html and css, you don’t need Django
But if you want to add a backend you would use Django
Okay so Django would not be good for this task?
If you are just wanting to style, no, but if you want to implement a backend and things like that then use Django
Before worrying about Django, I would first learn html and css as you will need it to make a webpage
What do you mean by implementing backend 😅
Backend is the logic of the application and how it works behind the scene
Front end is what the user can see
You are wanting to do the frontend, or create and style the webpage like you see it in that image
The UI
Ohh yes now I got it
So before doing Django or any major web development, learn HTML, CSS and JavaScript
Html and css are relatively easy (css does get wacky though)
Okay understood
Django is a framework for making the backend and API’s
but it does have the ability to render html templates and static files as I said
You can use frontend JS frameworks along with it though
Yeah But Js would be overwhelming for me as I haven't done Html Css. I will go with what you suggested in the first place
Shit man now my project will get delayed
You have to learn before doing projects man
don’t worry about it, I’m sure you will produce a great project when the time comes
What do even want to make?
you*
Actually in my project there's a really small part of creating a web page
Basically my project is if someone uploads a scanned image of ingrediant list of certain product, I will extract words from it and then display some info about all the ingrediants
This way one can know what they are consuming
is there a way
to add params to url for
in flask
i tried redirect(url_for(f'index?msg={msg}')) but that didn't work
Hello everyone
I am trying to roll out a small test app to Heroku that includes a front end client (an Angular app) and an API server (written in .Net Core). I am using Docker images to do this. According to the documentation for containers on Heroku, you are able to push multiple containers to a single Heroku app. I have successfully set it up so the webapp is displayed when you navigate to the URL, but I can't seem to find a way to communicate with the server. Is there a specific URL that links to a specific container? If not, then what kinds of systems can you build with multi-container apps on Heroku?
The documentation does not seem to clarify this. The only answer I could possibly come up with for this is to use one container to receive and answer incoming HTTP requests, while the other containers act as workers for background tasks (although the documentation doesn't seem to detail how the two types of containers would communicate in this case).
Hi, I'm trying to do db migration with flask, flask_sqlalchemy
this is my code ```py from flask import Flask, jsonify
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_restx import Api, fields, Resource
from flask_marshmallow import Marshmallow
from flask_migrate import Migrate
from flask_swagger_ui import get_swaggerui_blueprint
app = Flask(name)
Init config
app.config.from_object(Config())
Init db
db = SQLAlchemy(app)
migrate = Migrate(app, db)
Init ma
ma = Marshmallow()```
after this commands in the terminal ```py flask db init
py flask db migrate -m "Initial migration."
I do have am igration folder created after first command
but after the second I got this error
TypeError: get_engine() missing 1 required positional argument: 'app'```
Hi. I'm using flask-sqlacodegen to create the models for an already existing MySQL database that I want to connect to a Flask API I'm developing.
When I check the outfile, I see that one table is created as t_aus_postmeta = db.Table() while the rest of them are created with the class constructor I already know, class DatabaseName(db.Model):
What is the reason for that difference? Will this affect the way in which I interact with the database?
do not worry, javascript is not very had for learn :)