#web-development

2 messages · Page 213 of 1

native tide
#

just for reference, my urls.py is configured like this @frank shoal

dusk portal
#

have anyone used lib called
django-private-chat

frank shoal
#

a long (generally) is a 64 bit integer.

#

it is not a long string.

native tide
#

the name is kinda confusing lol

frank shoal
#

oh, long is the name

native tide
#

yeah the long version of the url

frank shoal
#

You should still consider using a query parameter instead.

native tide
#

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

frank shoal
#

query is always passed to the backend. It's usually in a request variable

#

I guess something like this. ```py
def do_something(request):
print(request.GET.get('url', ''))

native tide
#

ok, i'm gonna try to wrap my head around this

#

thanks a lot

azure shard
#

run it again?

golden bone
# azure shard 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

warped aurora
#

how do grab a jinja template variable in my javascript

crude badge
#

Celery question:
What is the ‘socket_timeout’ parameter in BROKER_TRANSPORT_OPTIONS used for?

#

For Redis

wheat verge
#

I am working with django. The app works fine locally but when I upload it on heroku I get the 500 error

left tangle
#

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

native tide
#

Should url encoding be done server or client side?

surreal portal
#

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.

golden bone
golden bone
surreal portal
#

The ones I'm attempted to use are --headless and --incognito

golden bone
surreal portal
#

Ok so iirc it protects from malicious content. I'm using Selenium for webscraping so it's best if I keep both flags on?

modest hazel
#

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

golden bone
heavy breach
#

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?

nimble thorn
#

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 ?

scenic furnace
#

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.

native tide
#

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

golden bone
thin dome
#

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'] }}

indigo kettle
#

yes but you access it with i.name

thin dome
thin dome
#

do we have to load anything in template to use {% set a = ... %}

sharp dove
#

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

harsh helm
#

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

inland oak
#

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

smoky forum
#

Is there a way to get an app in a app store without paying?

harsh helm
inland oak
#

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

harsh helm
#

Ah, thanks for giving me advice

cerulean badge
#

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

twilit needle
# harsh helm So I should only use Cypress or Selenium for larger scale projects, and even the...

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

mental summit
#

<@&831776746206265384>

open sigil
#

this too

mental summit
round patio
#

and #bot-commands

native tide
#

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?

wild iron
#

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

native tide
#

Hello guys I need some help the media query isn't working for me i'm using SCSS

glacial estuary
#

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

mental summit
#

You used a = instead of a :

glacial estuary
#

ohh

#

yeah didnt notice that

#

c++ creeped up in there

#

lel

#

thx

rough garnet
#

how can I run and monitor a long running background job in flask?

west skiff
#

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.

inland oak
west skiff
sharp dove
#

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

west skiff
sharp dove
#

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

west skiff
#

which line is this error for? i can't tell if its for those u sent above

whole garnet
sharp dove
#

im mac

#

thats how it is lol

whole garnet
#

Ohh kk

sharp dove
#

my syntax was wrong in def(home)

#

but thank you so much for trying

west skiff
#

Oh okay np

tight pike
#

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

serene prawn
tight pike
#

🥺 omg thank youuuuuuuu

#

was going crazy

cerulean badge
#

(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()
wanton storm
#

What's this?

cerulean badge
# wanton storm 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.

cerulean badge
# cerulean badge (django) in a consumer, does it stack the messages sent from client to server an...

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"])
native tide
#
  elems = driver.find_elements_by_xpath("//a[@href]")```

Hello what is it ?
manic frost
#

"deprecated" means that for whatever reason they will be removed in some near future

native tide
dusk portal
#

make tuts on Kubernates

cerulean badge
languid raptor
#

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.
??

serene prawn
golden bone
serene prawn
languid raptor
serene prawn
languid raptor
serene prawn
#

ORMs usually work with databases, API is not a database

#

You can convert your json responses to objects

languid raptor
languid raptor
serene prawn
#

What do you mean? 🤔

languid raptor
serene prawn
#

I don't really remember 😅

languid raptor
#

Fair

serene prawn
#

If you need to query multiple endpoints to get a full object you need you really have two choices:

  1. Do it manually
  2. 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

languid raptor
#

sales is composed of tickets which are composed of menu items

languid raptor
#

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.

strange charm
#
    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

round cedar
#

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?

golden bone
round cedar
#

Tbh i am looking for all 3 things mobile download + web app i hope it should be possible in react js to do that

jolly dove
#
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

drifting radish
#

How can i add picture 3d (blend) to my webstie with django?

brisk mortar
#

Can someone please tell me how to connect mongoDB to Django ?

trim chasm
#

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

stiff copper
#

(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:

native tide
#

hey is anyone aware on how to render forms/database like its done in django-admin, but on a users panel

lunar adder
#

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

native tide
#

how can I get the input values of a HTML file using Python?

(I need this to also work on Replit)

golden bone
#

And I believe that would work on replit if the HTML is a file is part of your repo

sharp dove
#

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

zealous lodge
#

wait web can develop by python? i thought just javascipt and php

inland oak
inland oak
wide dove
#
 directory.
#

guys please help

#

i set the environment varibale for flask on windows

#

but still getting this here

cerulean badge
#

(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?

dusk portal
outer apex
indigo kettle
cerulean badge
loud bridge
#

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

nimble thorn
#

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

golden bone
# nimble thorn i was thinking that i might need selenium, however i thought maybe python `reque...

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

lavish prismBOT
#

Hey @native tide!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

thick sinew
#

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?

undone laurel
#

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?

simple tendon
#

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?

broken mulch
#

how do I center a text right in the middle of the screen

#

and it's only within its container

golden bone
golden bone
nimble thorn
#

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 😕

broken mulch
errant ledge
#

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

surreal badger
#

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

golden bone
golden bone
surreal badger
#

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?

lethal junco
#

please help, I'm having this error when running the Dockerfile

#

I want to run it via localhost using manage.py

visual cedar
#

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?

native tide
#
<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

visual cedar
#

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

golden bone
# lethal junco

I think it's telling you setup.py doesn't exist in the working directory. If it does, maybe an issue of file permissions?

golden bone
native tide
golden bone
#

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

native tide
lethal junco
#

should I add something on that configuration?

unborn lion
#

Is it possible for python to find out what website is open on your pc?

inland oak
unborn lion
#

but do you know how to do it?

inland oak
#

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

unborn lion
#

ohk

near ravine
#

@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

wet sparrow
#

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

mental summit
#

You probably shouldn’t delete database.db. That’s the file that acts as the database.

near ravine
#

how to block all websites except 2 in python?

inner bramble
near ravine
#

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

inner bramble
#

From what I understand, you want your Python program to detect what website you're on and act on it in the background?

inland oak
#

while it is still possible in python, it is by magnitude harder

near ravine
#

ok

near ravine
inland oak
#

then do you deed with the acquired data

near ravine
#

ok

near ravine
#

im not sure i get you

#

do you have sample code or something?

inland oak
#

or find examples of the code in google

inland oak
#

although official docs are better

near ravine
#

but why do i need to make an extension tho

inland oak
#

extension is in browser application, it has access to do the job you wish

near ravine
#

ok.........

near ravine
#

@inland oak update

#

i made the extension

near ravine
#

now how can i integrate that with python?

#

@inland oak

inland oak
inland oak
#

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

#

to acquire list of allowed-white listed urls or any other data

#

in similar requests you can input data to python

near ravine
near ravine
proven root
#

can somebody help me to find the code for this problem , please ..

lavish prismBOT
#

8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.

proven root
lavish prismBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

inland oak
native tide
#

We don't help people to find code for a problem. If you did something and you're stuck, we are happy to help.

alpine crypt
#

pls get me out of this server

thorn igloo
flint wasp
#

Hiii, Can anyone please guide me in understanding CSS box model

rare iron
#

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

rare iron
flint wasp
#

I need some understanding on alignment of boxes, Tutorials and videos weren't able to help me

digital bay
# flint wasp I need some understanding on alignment of boxes, Tutorials and videos weren't ab...

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...

hybrid iris
#

Okay so I use flask.py and I keep getting an error on auth.py and I have 3 routes and I keep getting a syntax. I can't send screenshots right nowas I am at school, but at 4pm CST if someone who can help would ping me I'll send them.

native tide
#

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?

ocean slate
#

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

golden bone
alpine crypt
thorn igloo
thin marten
lavish pumice
#

ok
JS or TS?

serene prawn
#

If you're already familiar with js and build tools i'd say ts

brisk mortar
#

How to make it so that there is a dot before the capital letter /::marker

serene prawn
#

I'd try using unordered list if you can

hazy wolf
#

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

serene prawn
hazy wolf
#

i can't change sadly its for my school and i have to learn how to use the TDD method with django test system

serene prawn
#

I think you could ask your teacher if you can use pytest since most developers use it instead

hazy wolf
#

someone already asked he's one of these annoying teacher yk

serene prawn
#

It's still testing, pytest is just more modern and is easier to work with

#

What kind of help do you need then?

hazy wolf
#

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

hybrid iris
thin marten
#

ill take a look if you post it

hybrid iris
#

Well I'm at school.

thin marten
#

ah ok

hybrid iris
#

Yeah,

wicked ice
#

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'```

outer apex
#

Also, what's MySQLdb.cursors? Is it from the mysql package, or is it something you created?

sonic niche
golden bone
sonic niche
#

display the contents of a json file like in that link. I figured it out

lethal void
severe current
#

hey guys,

#

do you think that a rubyonrails developer should switch to python webdevelopment

#

like flask django or something like that

north wigeon
#

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?

severe current
#

mmh like a cookie?

inland oak
#

so... what would be the point

serene prawn
twilit needle
sacred crane
#

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

rotund perch
#

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.

inland oak
#

JWT tokens as a choice should work fine

#

procedure

  1. Client AUTHed in your another framework, your framework has SECRET_KEY_1 and sent a sticky cookie with JWT stuff to identify user
  2. Your user goes to Django Framework, with same SECRET_KEY_1, you validate sticky JWT token, success
rotund perch
#

it need some configurations on settings.py on the default authentication or similar right?

inland oak
#

Here how to do it in python

#

find same thing in your other framework/language

rotund perch
#

Okay, Thanks!

inland oak
#

something like that

#

(heavily outdated page, but probably stull working example)

rotund perch
#

will check that! appreciate your help

native tide
#

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?

dense slate
#

djangogirls tutorial is very good

cursive root
#

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
dense slate
proven elk
#

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

frigid elm
#

Hey guys!

#

How I can add an instance in form use FormView Class?

#

in my view

sonic niche
#

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

still yew
#

Or was?

#

Was this site used to dump code at one point?

#

Anyone heard of this site before?

rocky cradle
#

The Python website looks quite bad in my phone, am I the only one?

indigo kettle
#

@rocky cradle I mean, probably not?

#

The wiki site look better in desktop mode on my phone actually

rocky cradle
drifting radish
#

I have problem with three.js

native tide
#
driver = webdriver.Chrome(service=Service(ChromeDriverManager(log_level=0).install()), options=options)

WebDriver.init() got an unexpected keyword argument 'service'

hybrid iris
#

@thin marten Sorry it took so long I've been fixing my PC.

thin marten
#

try .models not models

hybrid iris
thin marten
#

can you send more code of where you are trying to import it too and where its importing from?

thin marten
#

whats the code inside the models file

hybrid iris
#

@thin marten

thin marten
#

one moment

#

try importing the database before importing the user

#

so change their order in the list

thin marten
#

are you able to post the full tracebacks?

thin marten
#

ah i see whats wrong, your folder structure isnt setup correctly

thin marten
# hybrid iris 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

hybrid iris
#

@thin marten

#

I still need help i TRIED.

thin marten
#

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

thin marten
#

send a picture of the file structure

hybrid iris
thin marten
#

hold on

thin marten
#

you may want to rename the folder from views since it will likely cause namespace conflicts (in the example i put)

thin marten
#

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

hybrid iris
#

@thin marten

thin marten
#

nice, what was the issue?

hybrid iris
#

I didn’t have a database.txt

#

For it to save the stuff hence the DB issue

#

@thin marten

thin marten
#

ah

hybrid iris
#

I’m gonna show my teachers tomorrow

twilit needle
#

You should just use simple random tokens for authentication

inland oak
twilit needle
#

I know this is a hot take

#

But trust me

inland oak
#

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

twilit needle
inland oak
twilit needle
inland oak
# twilit needle ??

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

twilit needle
#

Alright, what's in the cookie?

inland oak
#

we just read his side car to the request

inland oak
#

capable to carry up to 4k of information

#

4 kilo bytes

twilit needle
#

I don't understand what you mean tho

#

How's this related to jwts

#

🤔🤔

inland oak
#

we send JWTs in Cookies

twilit needle
#

Hmm but why

inland oak
#

we store JWTs in Cookies

twilit needle
#

Is it to be stateless?

inland oak
# twilit needle Hmm but why

Because it is convinient and better secure! Frontend code has no access to Cookies with javascript forbidden state flag in them

twilit needle
#

Imo statelessness is impossible when you handle authentication

inland oak
#

All auth stuff of backend is obscrured away from frontend 😉

twilit needle
#

You could send simple random tokens instead

inland oak
#

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

twilit needle
inland oak
#

WHY!?!?

#

it is additional request to SQL Database

#

it is uneffefficient!

#

and I would need validate every time from database!!!!

twilit needle
inland oak
#

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

twilit needle
#

Okay, but this involves tradeoffs too

#

You cannot invalidate tokens at once

#

You'll need a blacklist

inland oak
#

I can put inside as much invalidating things as I wish

twilit needle
#

Which makes the whole flow stateful

inland oak
#

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

twilit needle
#

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

inland oak
#

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

twilit needle
#

It's in the article I linked above

twilit needle
#

alright though, this was a fun debate/ discussion lol

serene prawn
#

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

wild iron
#

in django while registering a new user how do i check if that username/email is already registered or not

serene prawn
wild iron
#

ahh lemme try

serene prawn
#

essentially where username = 'Username' or email = 'YourEmail'

wild iron
#

ah okay

wild iron
wild iron
#

alright thanks

#

@serene prawn I tried to register with the same username and got this

serene prawn
#

username="username", you have to check with username that was send to your form

serene prawn
#

This is your form, could you show me how you're trying to create your user?

#

Or just more code pithink

wild iron
#

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")```
serene prawn
wild iron
#

lol i will just delete it, coz its taking too much space

serene prawn
#

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"))

wild iron
#

lemme try that out real quick

wild iron
#

thankss a lot mate

barren lava
#

I am looking for Python Website and application Jobs with Django, Flask, Fast API.

wild iron
#

it even worked for email, thanks a lot doctor

winter hearth
#

What's the difference between % and %- in Jinja?

inland oak
serene prawn
#

@inland oak You store both access and refresh tokens in cookies?

inland oak
serene prawn
#

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

inland oak
#

it could happen only if user has something like usafe plugins installed

covert trench
#

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?

  1. 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=user and when normal user wants some data about shop using same view I don't want to filter it)
  2. 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)
random sand
#

django

#

help needed

#

cant figure out the problem

covert trench
#

What is your error?

native tide
#

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.

tropic blaze
#

Hey guys I am new django and wanted to ask is it compulsory to have a static folder in your django project?

frank shoal
tropic blaze
tropic blaze
stark tartan
stark tartan
tropic blaze
tropic blaze
mental summit
#

It holds image uploads

tropic blaze
wheat verge
#

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?

wheat verge
#

what code?

inland oak
wheat verge
#

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

dense slate
#

Look at open graph to setup your page to have meta information like this. It has to do with SEO if that helps.

wheat verge
#

thank you

flat frigate
#

guys my page keep reloading while i am streaming by openCV anyone know any solution to stop this reload?

buoyant cypress
#

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

dense slate
buoyant cypress
#

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

dense slate
#

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?

buoyant cypress
#

i'm using rest_framework

#

with simple_jwt

dense slate
#

So when you signup, you send a request to the api with the information.

buoyant cypress
#

yes

dense slate
#

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.

buoyant cypress
#

the thing is that when i send the data

#

how i know which user update

dense slate
#

I assume the cookie has user data in it.

#

I use django-jwt and it sort of handles all of that.

buoyant cypress
#

ok thanksss

quick isle
#

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

dense slate
#

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.

buoyant cypress
rare lagoon
#

Can you use bootstrap with flask?

quick isle
#

does anyone can help me with apache2?

#

and django

dull isle
#

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?

unique shore
#

Like a bot dashboard?

#

Check out

#

!pypi quart

lavish prismBOT
#

A Python ASGI web microframework with the same API as Flask

unique shore
#

!pypi quart-discord

lavish prismBOT
serene prawn
unique shore
#

I mean they should use the same database

dull isle
#

okay, that makes sense, can you point me to an article or video?

unique shore
#

Look at the py pi’s

#

!pypi quart

lavish prismBOT
#

A Python ASGI web microframework with the same API as Flask

unique shore
#

!pypi quart-discord

lavish prismBOT
serene prawn
#

You don't need quart for that 🤨

unique shore
#

yea ik

serene prawn
dull isle
unique shore
dull isle
serene prawn
unique shore
#

mhmm

serene prawn
#

@dull isle You can connect flask app and discord bot to the same database pithink

dull isle
#

okay, do you have a database reccomendation?

serene prawn
#

Postgres is good

unique shore
#

Postgres

dull isle
#

alright cool!

serene prawn
#

Personally postgres + sqlalchemy as an orm

dull isle
#

ill look into that, thanks, y'all

#

i dont know enough about backend to understand what you mean 😅

serene prawn
#

It's a popular python orm, you'd probably use it with flask

dull isle
#

okay, cool, ill look that up too

unique shore
unique shore
#

mhmm

serene prawn
#

prisma itself is not a relational database

unique shore
#

ik

serene prawn
#

sqlalchemy is working with sql databases (sqlite, postgres, mysql, etc)

unique shore
#

It’s an ORM

#

ahh so prisma isn’t just for only sql databases basically

serene prawn
#

Yep

unique shore
#

ok

#

it could still work though in some sense right?

#

as an orm

serene prawn
#

It won't work with sql databases 😅

#

it would work with prisma db

unique shore
#

ok

#

thanks for the info

serene prawn
#

Oh, actually, wait 🤔

unique shore
#

?

serene prawn
#

I actually meant cassandra 😅 It's a db that discord uses

#

Prisma should support sql databases

unique shore
#

ok

#

all good

unique shore
serene prawn
#

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

unique shore
#

Understandable

serene prawn
#

sqlalchemy supports a lot of weird cases, you could configure a lot of things pithink

frigid sigil
#

Hey guys!

tawdry chasm
#

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
frigid sigil
#

I would really appreciate if someone could help me on this, been stuck for a bit haha

serene prawn
#

e.g. Flask(template_folder="app/templates")

twilit needle
near ravine
faint cedar
#

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

icy kestrel
#

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?

inland oak
#

as a second, this is probably question for #career-advice channel, it is often discussed there

random sand
#

anybody help me

#

need help

#

can't understand what is the problem

dusk portal
dusk portal
# random sand ok

N yeah in 2nd func (i.e login) why did u pass HttpRequest)
request

#

Is enough

random sand
#

ok but it gives error

dusk portal
#

def login (request):
return render(request,pages/index.html)

dusk portal
crude stirrup
#

what's the difference between flask-login, flask-admin, and flask-security?

snow edge
#
{% 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

dusk portal
#

It's always use of . When we fetch remember that

#

N it will work

snow edge
dusk portal
#

Kinda impossible dude

#

See ur if statement

#

change it to
guild.icon.url

#

Not guild.icone_url

snow edge
#

icon.url wont work dude

dusk portal
#

Just try

#

As I said

snow edge
dusk portal
#

It's saying

#

U don't have any object named icon on the db (or this particular post)

snow edge
#

it is saying guild object has no attribute icon

#

the syntax is icon_url

dusk portal
#

Show me ur models

snow edge
#

I'm using a module called quart_discord

dusk portal
#

Ohh

#

But it isn't also loading ur if statement

snow edge
twilit needle
snow edge
#

but no

dusk portal
#

Wait lol

#

I'm sorry

#

@snow edge

snow edge
dusk portal
#

Ik solution of this

#

To check if

#

Just write
if guild.icon_url

#

Remove is not none

#

It itself checks

snow edge
#

ok i am trying

dusk portal
#

Yeah

#

N send ss too

dusk portal
snow edge
#

k

dusk portal
snow edge
#
<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

snow edge
twilit needle
#

I dont use jinja2 that much, the last time I did was to do server side template rendering

twilit needle
#

Alright, so lemme help you here

#

What's the error you are facing

snow edge
twilit needle
#

Could you do a quick test

snow edge
twilit needle
#

print(guild.icon_url)

snow edge
snow edge
twilit needle
#

Before you render the template

snow edge
#
@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

twilit needle
#

Show me the full route, please

#

So that I know what variables you pass in

snow edge
#
@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

twilit needle
#

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

snow edge
snow edge
#

but u can see the icon in ur client

twilit needle
#

Could you print the guilds you have to the console and check the icon URLs for each?

snow edge
#

okay just a sec

twilit needle
#

Just do

for guild in user_guilds:
    print(guild.icon_url)
snow edge
#

yeah it prints

twilit needle
#

So every guild has its icon url set

snow edge
#

but dosent count guilds with no icon_url

twilit needle
snow edge
#

these guilds dont get counted

#

with default icon_url

twilit needle
#

Well no, they are icons too, right?

snow edge
#

api ignores them

#

they are none

twilit needle
#

But I dont see any None in the terminal

snow edge
#

but it dosent count them too

twilit needle
#

How are you sure

snow edge
#

i clicked on each of the icons

#

to check

#

none of them are default icon url

#

i even counted

#

only them dont get counted

twilit needle
#

Well, maybe in those guilds you dont have administrator permissions

#

So you dont collect them

snow edge
#

i'm owner in them

twilit needle
#

Hmm, what is rendered in the browser?

snow edge
#

once with default icon r not rendered

twilit needle
#

Could you open devtools

#

And tell me the icon url for those servers

snow edge
#

ok

#

icon of the guild with no icon_url

#

but it dosent render

#

meaning it gets added but not rendered

#

html problem then ig

twilit needle
#

So.. the else block executes properly?

snow edge
#

yes

twilit needle
#

This might be a css problem too

#

Your red-border class maybe hiding it

snow edge
#

i tried to remove guild.class_color

#

it still dosent work

#
<img src="https://discordapp.com/assets/322c936a8c8be1b803cd94861bdfa868.png"/>
twilit needle
#
<img src="https://discordapp.com/assets/322c936a8c8be1b803cd94861bdfa868.png" />
#

Try this?

snow edge
#

ok

#

nope

twilit needle
#

Try pasting in some other url

snow edge
#

i tried adding another img. Dosent wok as well

twilit needle
#

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!

snow edge
#

ok thanks for your time :)

gentle ingot
#

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```
near ravine
#

sockets

inland oak
#

@stark tartan 😆

  File "<stdin>", line 1
    .
    ^
SyntaxError: invalid syntax
inland oak
#

or I am just too nervous due to my product coming to production launch. That could be too.

inland oak
# stark tartan 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!!!!!!

stark tartan
#

I just learn docker 😅

inland oak
#

I was just responsible for every part of the product alone. And I am a bit nervous if I was able to anticipate everything

stark tartan
inland oak
#

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 😉

inland oak
#

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

mint folio
#

@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.

inland oak
#

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

mint folio
inland oak
#

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

mint folio
#

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.

inland oak
#

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 😉

serene prawn
inland oak
serene prawn
#

Workers also can handle multiple requests if you use something like gevent worker class

mint folio
#

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.

inland oak
serene prawn
#

🤔 Not really

inland oak
serene prawn
#

Your app should be to handle simultaneous connections despite being sync

inland oak
#

I made sure to have a test with quering endpoint multiple times

#

including quering some simple endpoint with sleep(1)

serene prawn
#

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

inland oak
#

but if request contains time sleep(1)

#

it will wait 1 second before going to finish next request

serene prawn
#

sleep is not cpu bound though 🤔

#

Are you implying that gevent would just put requests into a queue?

inland oak
#

if uses async sleep, then perhaps not

serene prawn
#

It should handle them concurrently though, let me check 😅

inland oak
#

time.sleep is sync, it should prevent concurrency

serene prawn
#

Again, how was i able to receive a callback with gevent then? 🙂

#

First request won't finish until callback is done

inland oak
#

the trouble would be for second-third and e.t.c. request made in parallel

serene prawn
#

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

inland oak
# serene prawn Not a lot of sync stuff, mainly database and http calls 😉
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 😉

serene prawn
#

Users request can't be done until django is done processing second request(callback)

serene prawn
inland oak
serene prawn
#
from locust import HttpUser, task

class HelloWorldUser(HttpUser):
    @task
    def hello_world(self):
        self.client.get("/hello")
        self.client.get("/world")

😃

inland oak
#

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

inland oak
zealous oar
glacial portal
#

what's the difference between flask-login, flask-admin, and flask-security?

crude badge
#

Are any of you folks using remote development? What does your setup look like?

inland oak
#

but using it usually a really bad practice for me

crude badge
#

Why?

inland oak
#

so i don't do it

inland oak
# crude badge Why?

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

crude badge
#

I hear that.
But there are some benefits such as taking advantage of “unlimited” storage and better GPU cards etc

inland oak
#

I mean... I am having dev PC as Linux, it is not different in capabilities to servers in my case

fringe gate
#

anyone familar with leaflet/folium know how i would rotate a custom icon?

clear nymph
#

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

inland oak
#

try chmod 777 -r /path/to/linux/folder/with/media/static/files

#

it permits everything 😉

clear nymph
#

thanks i fixed

frank shoal
#

It's really chown www -r /path/to/static

autumn veldt
#

someone know how can i see if page is doing playing sound in selenium?

golden bone
inland oak
# frank shoal It's really `chown www -r /path/to/static`

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

rare lagoon
#

Whats the difference between a web framework and a web server?

golden bone
# rare lagoon 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

rare lagoon
#

So I can run a web framework with a web server if my app needs to?

golden bone
rare lagoon
#

Got it, thank you

split snow
#

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"
}
velvet quest
#

hello everyone , I am having a half day today, I have some work to do.

near ravine
pale topaz
#

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?

hollow ocean
#

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?

pure bison
#

could some one suggest me where to start django from ??

#

any resources if you could suggest to work my way through!

dapper lichen
warped aurora
#

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>```
tropic blaze
tropic blaze
#

Can anyone guide me I just want to create a webpage like this with Django -

unique shore
#

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

tropic blaze
#

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

unique shore
#

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

tropic blaze
unique shore
#

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

tropic blaze
unique shore
#

Backend is the logic of the application and how it works behind the scene

lapis basin
#

Front end is what the user can see

unique shore
#

You are wanting to do the frontend, or create and style the webpage like you see it in that image

lapis basin
#

The UI

unique shore
#

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)

unique shore
#

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

tropic blaze
#

Shit man now my project will get delayed

unique shore
#

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*

tropic blaze
tropic blaze
# unique shore What do even want to make?

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

unique shore
#

ahh ok

#

Gl with that

native tide
#

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

proven rock
#

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).

golden bone
feral night
#

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'```
crimson monolith
#

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?

native tide