#web-development

2 messages · Page 162 of 1

shadow belfry
#
           <form enctype="multipart/form-data" action="savetest_file.py" method="post">
                <p><input type="file" name="filename" accept=".wav"/></p>
                <p><input class="cta-btn align-middle" type="submit" value="Envoyer"/></p>
            </form>
#
import cgi, os
import cgitb; cgitb.enable(display=0, logdir="/log")

try: # Windows needs stdio set for binary mode.
    import msvcrt
    msvcrt.setmode (0, os.O_BINARY) # stdin  = 0
    msvcrt.setmode (1, os.O_BINARY) # stdout = 1
except ImportError:
    pass

form = cgi.FieldStorage()
# Get filename here.
fileitem = form['filename']
# Test if the file was uploaded
if fileitem.filename:
    fn = os.path.basename(fileitem.filename)
    open('upload/' + fn, 'wb').write(fileitem.file.read())
    message = 'The file "' + fn + '" was uploaded successfully'
else:
    message = 'No file was uploaded'

print("""
Content-Type: text/html
<p>%s</p>
""" % (message,))
#

I store the file send by form in upload folder and I can use the file but for the audio file I don't have the full audio send

compact surge
#

Why you dont close the file after opening?

shadow belfry
#

I can try to close it to see if something change

karmic maple
#
from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route('/')
def home():
  return "Hello"

if __name__ == '__main__':
    app.run(debug=True)
```What's wrong with cors here, it isn't working.
compact surge
karmic maple
#
Access to fetch at '<url>' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
shadow belfry
# compact surge Okey

I try this but nothing change : ```py
file_data = open('upload/' + fn, 'wb')
file_data.write(fileitem.file.read())
file_data.close()

compact surge
#

Why you use cgi?

#

I use Flask for making the word generator

#

I think the problem with cgi

#

And my file also uploading from html form

shadow belfry
#

Ok ok I will try flask

rugged scarab
#

Nvm got it, the problem I was using Chromes driver and using edge to check stuff out. Thanks btw

native tide
#

Hi! Does anyone can recommend a good Django 3 course?

ivory bolt
#

and what specifically do you want to learn

north oasis
native tide
#

I have some experience with modular systems such as Odoo

#

also i've some experience with PyTorch

native tide
#

😦

#

I'm searching for Django3 tutorial

north oasis
cerulean mortar
#

Hi I am having an issue with new url patterns. for some reason Django cant find my new url patterns and is displaying my old home page http response instead of my new one. here are some code snippets. any help greatly appreciated!

short venture
#

Hello all. I've a question about Django's ORM.

Say, I have an object named UpgradeRequest. Whenever a product's higher version is requested, this UpgradeRequest object is being created automatically. Currently, it has 3 statuses. 1-) Approved, 2-) Rejected, 3-) Cancelled.

without_upgrade_request = UpgradeRequest.objects.filter(
user_profile=OuterRef("user_profile__pk"),
status__in=[2, 3],  # Rejected and canceled won't be shown.
)

Product.objects.filter(user_profile__user=self.request.user)
.annotate(without_upgrade_request=Exists(without_upgrade_request))
.filter(without_upgrade_request=False)

I'm currently checking if a user has requested to upgrade a product or not. But since one product can have more than one statuses in past, if that object has an UpgradeRequest object with status cancelled or rejected won't be shown even if it has an UpgradeObject with approved status currently.

How can I exclude the past statuses (rejected and canceled) if that object has a UpgradeRequest object with approved status?

cerulean mortar
#

the products and customer urls return a 404 😦

obsidian steeple
cerulean mortar
#

idk why it is that though as my httpresponse is just set to 'home'

native tide
#

how to do smth like this ```js
(function () {
const second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24;

let birthday = "Jun 8, 2021 16:54:00",
countDown = new Date(birthday).getTime(),
x = setInterval(function() {

    let now = new Date().getTime(),
        distance = countDown - now;

    document.getElementById("days").innerText = Math.floor(distance / (day)),
      document.getElementById("hours").innerText = Math.floor((distance % (day)) / (hour)),
      document.getElementById("minutes").innerText = Math.floor((distance % (hour)) / (minute)),
      document.getElementById("seconds").innerText = Math.floor((distance % (minute)) / second);

    //do something later when date is reached
    if (distance < 0) {
      let headline = document.getElementById("headline"),
          countdown = document.getElementById("countdown"),
          content = document.getElementById("content");

      headline.innerText = "Ended!";
      countdown.style.display = "none";
      content.style.display = "block";

      clearInterval(x);
    }
    //seconds
  }, 0)

}());

versed python
ivory bolt
#

really a few things here and there with authentication

#

corey shafer is good but you can also check out coding entrepreneurs

#

I believe coding entrepreneurs has a structured course

#

and then when you want to get into specifics, you can check out corey shafer, Denis Ivy

#

I also feel that the django documentation is supremely good! After a certain level, you'll find yourself relying less and less on tutorials

#

I myself use django 3.2

ivory bolt
#

happens a lot

ivory bolt
ivory bolt
#

when importing path and include, probably try removing .conf

ivory bolt
cerulean badge
#

no it didn't work bro

modern dock
subtle otter
#

Hello , so i got a website where i'm trying to use a python script in , the script takes the uploaded files and removes duplicates and sorts them into new folders depending on their extension . how i want this to happen is first of all the user uploads the file then chooses the type after that he clicks on . than he gets the interface that i'm gonna send in screenshot next where he runs the python script (this interface is in the same page just done some js to hide the other one and display this one).
What i want to do is the post request doesn't refresh that page so the js code works

#

this is the new interface

glad creek
#

ok so I git cloned a project, did flask run than closed the terminal
now am doing a different flask project and when I do flask run it displays the previous flask project? how do I fix it, I have no clue

proud lintel
#

Can anyone tell me is fastapi can be used for heavy load application?

fiery stirrup
#

hey guys, what is the data attribute of "Visit W3Schools.com!" in -
<a href="https://www.w3schools.com">Visit W3Schools.com!</a>

ivory bolt
ivory bolt
#

assuming you're using django

subtle otter
#

lemme upload it to code pen one sec

ivory bolt
#

alright

subtle otter
#

here it is

ivory bolt
#

checking it out rn

#

so @subtle otter you are returning users to an index.html template after a successful upload with the valid file validations correct?

subtle otter
#

yea but i don't want that to happen

#

i want it to upload the file and don't refresh the page

ivory bolt
#

wait, you don't want it to refresh the page?

subtle otter
#

yea

ivory bolt
#

so you want it to happen asynchronously?

subtle otter
ivory bolt
#

I'm not a 100% sure here but the way to do that must be via some sort of use of websockets

#

ohh

#

so is it one form after the other?

#

Basically

subtle otter
#

i read that ajax could be used but limited knowledge with that too

ivory bolt
#

I get that

subtle otter
#

yea the first one for the upload the second one it calls a python script to start working

ivory bolt
#

wait a minute -- is the python script in any way dependent on the file upload?

#

cuz otherwise you just first validate the form and then move onto the second form before processing the post request

#

which means that

#

write the same POST logic for both

subtle otter
#

yea it takes the uploaded file and do some work on them

ivory bolt
#

ohhk

#

async then right

subtle otter
#

yea how could i do that pls?

ivory bolt
#

well…I'd need to check out the docs

#

can you tell me what exactly the script is doing and where it's running?

subtle otter
#

what it does is take a folder with webshell files sorted by their extensions then hash them using md5 then checks for duplicates using their md5 , when the duplicates gets removed it adds them to a new folder that is structured the same as the one they were in

ivory bolt
#

NGL that's a pretty good level of security

#

wait a bit

#

is there anyway to get this script running client-side instead of server-side

subtle otter
#

it's been sent to me by a teacher and he told me to work with it without chaning anything , so i don't think i could or know how to xD

ivory bolt
#

I hear that xD

#

k so check this out

#

their upload section of the code

#

you just write data

#

flask is supposed to work asynchronously

#

but your logic is kinda messed up

#

k so it's pretty similar to django so I'll write something that should be pretty similar to what you want to do

ivory bolt
#

@subtle otter can I get back to you tomorrow?

subtle otter
#

@ivory bolt for sure for sure man , imma add u and just lemme know when ur on

#

Thanks a lot m8

ivory bolt
lethal kite
#

Hello everyone, can someone help me with a question with django?

lethal kite
# late gale go ahead

Can I edit a form from my ListView, I mean, I want to edit a specific field of my model in my ListView and update only that field in my view,I was thinking use patch method but i'm not sure how to do this, so how can I do this?

#

Idk if u see my code u get a better idea that i'm trying

late gale
lethal kite
#

yeah and update or delete it, only that field

late gale
lethal kite
late gale
#

and use FormMixin

lethal kite
#

let me share with u my code

late gale
lethal kite
#

from django.db import models


class RequestContract(models.Model):
    PENDIENT = "Pendiente"
    APPROVED = 'Aprobado'
    REJECTED = 'Rechazado'
    CANCELLED = 'Cancelado'

    STATUS = (
            (PENDIENT, 'Pendiente'),
            (APPROVED, 'Aprobado'),
            (REJECTED, 'Rechazado'),
            (CANCELLED, 'Cancelado'),
    )

    objective = models.TextField(
        verbose_name='Objeto',
        blank=False
    )

    request_date = models.DateTimeField(
        verbose_name='Fecha de solicitud',
        null=True,
        blank=False
    )

    status = models.CharField(
        verbose_name='Estado',
        max_length=30,
        choices=STATUS,
        default='Pendiente'
    )

    def __str__(self):
        return self.objective


#
class RequestContractForm(forms.ModelForm):
    class Meta:
        model = RequestContract
        fields = ('__all__')

#
class RequestContractList(ListView):
    model = RequestContract
    template_name = "contratacion/contratacion_list.html"
    paginate_by=5

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['action_new_url'] = '/requestscontracts_create/'
        context['form'] =  RequestContractForm()
        return context
late gale
lethal kite
#
{% block table %}
    {% block table_head  %}
        <div class="table-responsive">
            <table class="table table-striped table-bordered table-hover dataTables-example text-center">
                <thead >
                    <tr class=>
                        <th class="text-center">Objecto</th> 
                        <th class="text-center">Valor Total</th>       
                        <th class="text-center">Valor Periodico</th>                       
                        <th class="text-center">Fecha de Solicitud</th>
                        <th class="text-center">Estado</th>
                        <th class="text-center">Acciones</th>
                    </tr>
                </thead>
    {% endblock table_head  %}     
    {% block table_body%}       
                <tbody>
                    {% for contratacion in object_list %}
                    <tr>
                        <td>{{ contratacion.objective }}</td>
                        <td>${{ contratacion.total_value}}</td>
                        <td>${{ contratacion.periodic_value}}</td>
                        <td>{{ contratacion.request_date}}</td>
                        <td class="status">{{contratacion.status}}</td>
                        {% block actions%}
                        <td><div class="ml-5">
                        <a href= "{% url 'contratacion:contrato_update' contratacion.id  %}" class="btn btn-primary btn-sm"> <i class="fa fa-pencil-square-o fa-lg"> </i></a>
                        <button class="btn btn-danger btn-sm" data-toggle="modal" data-target="#myModal6"> <i class="fa fa-times-circle-o fa-lg"></i></button> 
                        {{form.status}}
                        {% endblock actions%}
                    </tr>
                    {% endfor %}
                </tbody>
                   {% endblock table_body %}
            </table>
#

well this is basically the problem

#

My listview shows me, all the content of my database using object_list

late gale
#

that's why it's listview

lethal kite
#

yeah

lethal kite
late gale
#

Add formMixin

#

before ListView

#

don't forget to import it

#
class RequestContractList(FormMixin,ListView):
...
#

from django.views.generic.edit import FormMixin

lethal kite
#

If I add, formMixin to my list view, I can render my form in my view and update the specific field that I want to?

late gale
#

unlike function views

#

try it and tell me if it works

#

and also read that doc

#

cause FormMixin also needs some functions with it

#

like form_valid()

lethal kite
#

ok, i'll try

#

I have a question this is the only mode that i can do this or i can use override the patch method and do the same?

#

can overide*

late gale
#

before adding FormMixin

#

waait

#
class RequestContractList(ListView):
    model = RequestContract
    template_name = "contratacion/contratacion_list.html"
    paginate_by=5

    def get_context_data(self, **kwargs):
        context = super(RequestContractList,self).get_context_data(**kwargs)
        context['action_new_url'] = '/requestscontracts_create/'
        context['form'] =  RequestContractForm()
        return context
#

try this

#

context['action_new_url'] = '/requestscontracts_create/' is this url right-written ?

lethal kite
late gale
#

u can add action to form like

<form action'{% url 'URLNAME' %}'>
..
</form>
#

without adding it to context

lethal kite
#

I can delete it and will not affect anything

late gale
#

just tell me when form is displayed

#

btw

#

to add a form u need to do it like this

<form>
{% csrf_token %}
{{form}}
</form>
#

u cant add it like u add it in html

#

it should be between form tags

#

and dont forget the token

lethal kite
#

This is basically the result

late gale
#

where's the form

lethal kite
lethal kite
late gale
lethal kite
#

yeah i see that change in my table

#

and see*

terse timber
#

Hello guys, I'm not sure if this is the right channel to ask this, but I'm having trouble understanding how I'm supposed to get different strings from a text file in the requests module.
To be more specific, this is my code so far:

    db = file.read().splitlines()
    lineByLine.append(db)

for line in lineByLine:
    response = requests.post(url, headers=hd, data=db[0], db[1], db[2])```

The issue is in `response = requests.post(url, headers=hd, data=db[0], db[1], db[2])`, where I don't seem to find a way to send different items through the `data` bit since I can't use commas to separate the index.
deep tinsel
#

Try setting data as a list e.g. response = requests.post(url, headers=hd, data=[db[0], db[1], db[2]])

terse timber
#

I've tried that before, but I'm getting ValueError: too many values to unpack (expected 2)

#

I also want to mention that the text file contains different JSON payloads in each line, which might be what's causing the issue in the first place

deep tinsel
#

That's right then. The format is busted

#

You may need to do something like this: response = requests.post(url, headers=hd, data=[json.loads(db[0]), json.loads(db[1]0, json.loads(db[2]]))

terse timber
#

still the same thing feelsbadman
I've also tried setting up a different variable so that I can then update it with information from each index, but I can't get rid of the "too many values" error message

deep tinsel
#

provide the raw value of db after the file is read so we can see the format of the data

native tide
#
response = requests.post(url, headers=hd, data=[Json.loads(db)[0], Json.loads(db)[1], Json.loads(db)[2]])```
terse timber
#

here's what the text file contains:

{"profile": {"firstName": "Test2", "lastName": "User2","email": "test.user2@liviu.com","login": "test.user2@liviu.com"}}
{"profile": {"firstName": "Test3", "lastName": "User3","email": "test.user3@liviu.com","login": "test.user3@liviu.com"}}```

The way I took the info out of it was by using

```with open('users.json', 'r') as file:
    db = file.read().splitlines()
    list.append(db)```
deep tinsel
#

Looks like valid JSON per-line

terse timber
terse timber
deep tinsel
#

Try something like this:

json_db = [json.loads(item) for item in db]
response = requests.post(url, headers=hd, data=json_db)
terse timber
#

Nope, not it's giving me
ValueError: not enough values to unpack (expected 2, got 1) xD

#

I don't understand how I can't manage to work around these errors while everything is perfectly okay both in the file and in the variables

native tide
#

print(db[0], db[1]) and send what you get.
If you still get the same error try print(db[0])

terse timber
#

every time I print everything it shows the correct output. Here's the output for the above

{"profile": {"firstName": "Test1", "lastName": "User1","email": "test.user1@liviu.com","login": "test.user1@liviu.com"}} {"profile": {"firstName": "Test2", "lastName": "User2","email": "test.user2@liviu.com","login": "test.user2@liviu.com"}}```
native tide
#

try print(db[2]) only. I think this will cause the error.

terse timber
#

Nope

#

It gives the correct output

{"profile": {"firstName": "Test3", "lastName": "User3","email": "test.user3@liviu.com","login": "test.user3@liviu.com"}}```
native tide
#

Where does the error "Too many values" point to? Send the whole error if you can.

terse timber
#

Here's the entire error:

    response = requests.post(url, headers=hd, data=json_db)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\api.py", line 119, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\sessions.py", line 528, in request
    prep = self.prepare_request(req)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\sessions.py", line 456, in prepare_request
    p.prepare(
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\models.py", line 319, in prepare
    self.prepare_body(data, files, json)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\models.py", line 510, in prepare_body
    body = self._encode_params(data)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\models.py", line 97, in _encode_params
    for k, vs in to_key_val_list(data):
ValueError: not enough values to unpack (expected 2, got 1)```
deep tinsel
#

can try response = requests.post(url, headers=hd, json=json_db)

terse timber
#

that actually worked :0 The only thing that I need to fix now is the way the script sees the body since I'm getting an error message from my company that the body is not well formed

#

It usually is because of the double quotes in it and I have to add just some normal quotes

#

thanks a lot guys!

deep tinsel
native tide
deep tinsel
#

json instead of data parameter

deep tinsel
#

Docs don't make it clean, but I think data needs to be plaintext maybe

native tide
#

Ohh

#

I think another solution is

response = requests.post(url, headers=hd,  data=json.dumps(json_db))```
terse timber
#

welp, the problem now seems to be that json_db is an array and is not taking each value individually feelsweirdman

terse timber
native tide
terse timber
#

as in indexing every JSON body

terse timber
#

well yeah, but it still gives the entire file's data instead of iterating through each one of the lines

stone parcel
#

I have used python before for coding. However I have never used python for web development. I have a course project that requires me to develop my web application using Django. Any recommendations for online tutorials or where to start??

native tide
terse timber
#

I know that 😄 My original question was how I can iterate through each line when using the data parameter, unless I'm not uderstanding what you're trying to say

tight lake
#

hello

native tide
#
for line in json_db:
    print(line)```
Like this?
tight lake
#

i need some help about django

terse timber
tight lake
#

i have some problems with django.contrib.auth.models.Group, can anyone help me please?

terse timber
#

sure, what's the problem?

rose basalt
#

Hey I'm trying to set up a secure websocket server
however whenever I try and secure it i get errors [it works if I don't have SSL enabled]
atm the client says ssl.SSLError: [SSL] called a function you should not call (_ssl.c:1129)
Heres the code:
Server: ```py
import websockets, asyncio, ssl
async def hello(websocket, path):
name = await websocket.recv()
print(f"< {name}")
greeting = f"Hello {name}!"
await websocket.send(greeting)
print(f"> {greeting}")
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain('origin.pem', 'private.pem')
start_server = websockets.serve(hello, "0.0.0.0", 87, ssl = ssl_context)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

Client: ```py
import asyncio
import pathlib
import ssl
import websockets
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain('origin.pem', 'private.pem')
async def hello():
    uri = "wss://socket.ganer.xyz/gsdgsdfg"
    async with websockets.connect(uri, ssl = ssl_context) as websocket:
        name = input("What's your name? ")
        await websocket.send(name)
        print(f"> {name}")
        greeting = await websocket.recv()
        print(f"< {greeting}")
asyncio.get_event_loop().run_until_complete(hello())```

heres the cloudflare worker: https://ganer.xyz/s/QLML1Y

heres the certs [these work for my main website] https://ganer.xyz/s/iqmjim
#

pls ive gone through two help channels and no replies

tight lake
balmy lintel
terse timber
tight lake
tight lake
dense slate
#

Hey all, quick question about JWTs. I am able to login and obtain a token in a React+Django app but I'm confused on how verifiy/refresh are intended to work. If I hard-refresh the page, my logged in state is lost, and so is this where verify comes in to reset that state?

mighty meadow
#

save your JWToken in any form you like(e.g localStorage)

#

and bring it in every request

dense slate
#

can you elaborate on what you mean by bring it in every request?

inland oak
dense slate
#

I have it setup in react that an auth context wraps my app, and basically runs a check each time. My problem is that on a hard refresh, the token is nullified in state and so I'm "logged out".

inland oak
#

keep it more persistent in react

dense slate
#

i have it set in localstorage as well as a JWT

inland oak
#

nulify only if token verification returned 403

dense slate
#

So here's the thing, if I delete my JWT in client, my verification still succeeds.

inland oak
#

it should not be possible

mighty meadow
#

ok.. this may depends on how your framework wrapper works

inland oak
#

if you delete JWT, verification request could not be done

#

because you have no token

dense slate
#

Ok, so that's what I thought, but it does, both in the app and in the graphql client.

inland oak
#

something is wrong somewhere

native tide
#

hey all

dense slate
#

To get around the refresh problem, I've been saving the token in localstorage, and then I run verifyToken mutation to compare whether the localStorage matches the JWT.

#

However, that mutation still works if I delete the JWT.

#

So I thought maybe I don't understand something about how this works.

#

I'm in the bread help channel if we don't want to clog this one.

inland oak
#

make unit test on django part
that after passing no token/incorrect token, you would get 403 error

#

after you will correct django accordingly to this test

dense slate
#

I'm embarrased to say that I don't have much experience with unit testing.

inland oak
#

it would mean the error is left on react part with quite high chance

inland oak
# dense slate I'm embarrased to say that I don't have much experience with unit testing.
dense slate
#

Awesome, I'll take a look when I have a free moment

#

But I don't think it's necessary to debug this, yea?

inland oak
#

React community

dense slate
#

Ok thanks. So at least I know I'm not crazy and something is wrong here.

inland oak
#

our junior front end person experienced same problem I remember

#

I guess it is common problem

#

we have React + Django too

dense slate
#

I'm using django-graphql-jwt so I didn't code any of the verification bit. I assume that is all working as intended.

#

What was the solution?

inland oak
#

mm, I am responsible only for Django part of the deal.
I just pointed him to specific API request which does nothing, except gets information about user. At the same time it verifives token for still being correct in order to retrieve the information.

#

he uses it somewhere among his page movements to verify user being still logged in

dense slate
#

Precisely my issue.

inland oak
#

on my part I wrote good tests

#

to ensure that any incorrect token will not work)

#

made them in pytest

rose basalt
#

Hey I'm trying to set up a secure websocket server.
However, whenever I try and secure it using SSL i get errors [it works if I don't have SSL enabled, assuming i change wss to ws in the worker]
With this code the client says [SSL] called a function you should not call (_ssl.c:1129)

Server: ```py
import websockets, asyncio, ssl

async def hello(s, path):
data = await s.recv()
await s.send(data)
print("Got data:", data)

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain('origin.pem', 'private.pem')
start_server = websockets.serve(hello, "0.0.0.0", 87, ssl = ssl_context)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()Client:py
import websockets, asyncio, ssl

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain('origin.pem', 'private.pem')

async def hello():
async with websockets.connect("wss://socket.ganer.xyz/gsdgsdfg", ssl = ssl_context) as s:
await s.send("Test")
print("Got data:", await s.recv())

asyncio.get_event_loop().run_until_complete(hello())```
Cloudflare Worker: https://ganer.xyz/s/yQKyhz
Cloudflare Certs [these work for my main website]: https://ganer.xyz/s/iqmjim
Nginx VPS Config: https://ganer.xyz/s/FiGzaK

dense slate
#

@rose basalt I had to update the nginx to accommodate SSL to get websockets working.

rose basalt
#

whats the yum command to do that?

dense slate
#

something along these lines:

location /wsapp/ {
   proxy_pass http://wsbackend;
   proxy_http_version 1.1;
   proxy_set_header Upgrade $http_upgrade;
   proxy_set_header Connection "upgrade";
}
rose basalt
#

because im terrible at nginx

dense slate
#

Sorry man, I can't now.

#

Just google nginx websocket upgrade ssl. It's pretty straight forward.

rose basalt
#

i DM'd my config

inland oak
#

anyway. Just check expected behaviour in a test

#

that once you login, you can make data retriaval with this token

#

and if you pass incorrect token, data retrival will not work

inland oak
#

(in a django)

dense slate
#

Is that the correct usage? If my token used to check if the user is signed in is missing, then get the localStorage token and run the mutation to compare it to the JWT, right?

inland oak
#

umm. it sounds wrong

dense slate
#

Then what does the verify mutation actually accomplish?

inland oak
dense slate
#

when the user signs in, I setToken (boolean to say yes or no someone is signed in) in react. But this resets to null on a hard-refresh.

inland oak
# dense slate Then what does the verify mutation actually accomplish?

if user returned from some another page, or he was gone for a long time
but he still has his token stored on his side
he passes it to your django API.
django API tries to decode the token and get dictionary from it.

if it fails to decode (may be some precise error received for that from JWT library), you answer in API as forbidden, 403
and client side of user gets nulified his sign in, asked for relogin

if decoding succeeds, his sign in persists

dense slate
#

That's right. token is still stored on the client, but it is cleared from the state in the app.

#

so I need to basically re-establish him as logged in automatically from his token

inland oak
#

if you have token still stored, you can verify if he is still sign in or not

#

if you have no token left... then his is not sign in for sure. ask for relogin

dense slate
#

Correct

#

Problem is

inland oak
#

but it is cleared from the state in the app. I don't get the meaning behind this

#

I did not work with React closely yet.

#

I just got myself familiar how to deploy it)

dense slate
#

I'm not sure it will be too helpful if you don't know how state works in react.

#

Basically on login, I set the state of the user as logged in.

#

But it's in memory, so a hard refresh clears it and rerenders the code.

inland oak
#

mm, but token is still stored?

dense slate
#

On the client, but not in the app state.

inland oak
#

what's the difference between client and app state

dense slate
#

So I have to grab the token from the client, and sort of quickly remind the app that they are logged in.

#

client is your browser

inland oak
#

I thought react exists for user only on client side, there is no server side

dense slate
#

in this case

inland oak
#

isn't all your server side only django?

dense slate
#

Yes.

inland oak
#

so...

#

I don't get what's the difference between
On the client, but not in the app state.

#

react exists only on the client

dense slate
#

I don't know if I can explain the difference.

inland oak
#

if for some reason app state is not matching something

#

but you still have token

#

you can just use this token to verify from django API and extract info again

dense slate
#

That's what I'm asking. Is the verification mutation used to do that.

inland oak
#

and return your app state to correct state, is it not possible?

inland oak
dense slate
#

Sorry, yes. Is the verifyToken API used to compare two tokens whether they match and basically return a payload if true?

inland oak
#

when API recieves the token, it tries to decode it with your salt

#

if it decodes... it is verified (return True if you wish)
if not, then False

dense slate
#

Oh, yes, right. Sorry I misspoke.

#

Here's the state issue... if i log in and navigate, i'm fine. But when you refresh the page, React rerenders the code, and therefore everything is sort of reset. As far as I can understand it, I need to take the token from the browser after the refresh and verify it. After I verfiy it, I set the state of "being logged in" back to true.

inland oak
#

in order to create token your API uses SECRET_KEY to encode it

#

same SECRET_KEY must be used to decode it back)

#

if your SECRET_KEY got changed, token decoding will fail.

dense slate
#

I don't have a problem with decoding.

dense slate
#

Problem is, I can successfully verify without a JWT in my browser.

inland oak
#

how do you make verification

dense slate
#

Oh i know why...

#

christ.

#

I store the token in localStorage, get it on refresh, and then send that token to the API. That's why it works.

inland oak
#

so basically you area already doing that

dense slate
#

This is how I read to do it on SO.

#

Right

#

But they said that I need to do that, and then make sure it matches to the JWT in the browser - which I thought was what the verifyToken API call was doing.

#

But apparently not.

rose basalt
inland oak
#

mm I think I know why they mean

#

but I also think it is a wrong approach if they wished to do that

#

when you then send that token to the API
you retrieve all user information, including you could get another token to compare them

#

it would be wrong

#

because generated token change due to time of expiration

#

but...

#

if you store last token your generated for login

#

you can compare with it!

#

which I actually do too

#

or may be I don't. I don't remember 🤔

#

those are just different ways to enforce more strictly

#

that token is still valid

dense slate
#

Hmm interesting.

inland oak
#

if we will verify our token

#

with last one used for login

#

we verify that his last login was made from the same browser

#

and other browhers where he was logged, would get automatically denied

#

basically this is not needed for basic functionality, but could be useful for a more complex checking when token should work

dense slate
#

and what happens if the token expires in 2 minutes, and the user refreshes the page - it also would not work.

inland oak
#

yup.

#

in this case

dense slate
#

So this is where the refresh token comes into play?

inland oak
#

you need to get refreshed token on every API request

#

but those are just two approaches in my opinion

#

you can go with more long living token (more than 2 minutes)

#

to not bother with it

dense slate
#

the initial token?

#

I hear that is very insecure to leave a long access token.

inland oak
#

hmm... shrugs

#

it would be more secure to use short lived one

#

I would be afraid that...

#

if user makes several operations at once

#

that his sign in would not fail during that time if tokens are that often refreshed

dense slate
#

If someone logs in on a public computer, then that access token won't expire for a long time.

inland oak
#

I heard there is combination of long and short lived tokens used somehow together. probably it can be investigated.

dense slate
#

Yes, access and then the refresh token.

#

But this helped me understand a bit better. Thank you!

inland oak
#

so... after login I would generate only refresh token

#

and react would use it to generate very short expiring access tokens

#

huh.

dense slate
#

I think the access token (short, 5min) is create on login, and a refresh token (long, 7 days ,30 days,etc.) is stored in the DB.

#

Then it is used to create new access tokens when needed.

inland oak
#

I'll probably find some tutorial about it

dense slate
#

Oh for sure.

inland oak
dense slate
#

So far I have just used access and verify. I don't quite understand implementing the refresh part yet.

tight lake
inland oak
#

main separation to refresh and access tokens for situations

#

when Auth server and Resource server are separated servers I guess

#

if we have Auth and Resource server being the same one...

#

the meaning for Refresh+Access combintation would be much less.
the only meaning would be left for it, since in this way Refresh token would be used less often that short lived Access tokens

dense slate
#

Right

inland oak
#

plus

#

we can make sliding sessions... but hmm, wait a moment scrolling through my head.

#

if we would go with Refresh + Access tokens

#

we can for example change our Access tokens on every request

#

making our traffic more or less protected since every access token is very short lived one (it lives for one request only!!!)

#

while having refresh token used only if our access token got for some reason expired

dense slate
#

That's true.

inland oak
#

it would be I guess useful, if traffic sniffing is a concern

dense slate
#

I mean you can set how long the access lives for.

inland oak
#

it will heavily decrease how often sensetive token is exposed to traffic

dense slate
#

so is verify what is used to send with each request to the api to make sure the access token is still valid? and if not, use a refresh token to create a new one?

dense slate
#

ahhh

inland oak
#

this scheme would be more usefully working though, if you used more microservices

#

when Auth microservice is the only one having User database and capable to generate and verify refresh tokens

#

while other microservices verified only with access token

#

the meaning behind this to decrease load/traffic to Auth Server

dense slate
#

right

inland oak
#

splitting the load between more micrservices

#

but at least we get small security improvement with Refresh+Access tokens I guess

inland oak
#

even if we aren't having our services properly microserviced

dense slate
#

This describes using localStorage with JWT to fix refresh issue.

inland oak
#

I need to read a book about microservices%

#

already bought one, but the queue... I have a lot of books to go through before reaching that one

inland oak
#

I just realized how to apply all of this too all my microservices

#

it will finally make the access to them secure

#

or at least more secure than it was

rose basalt
#

alright asking this again

#

Hey I'm trying to set up a secure websocket server.
However, whenever I try and secure it using SSL i get errors [it works if I don't have SSL enabled, assuming i change wss to ws in the worker]
With this code the client says [SSL] called a function you should not call (_ssl.c:1129)

Server: ```py
import websockets, asyncio, ssl

async def hello(s, path):
data = await s.recv()
await s.send(data)
print("Got data:", data)

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain('origin.pem', 'private.pem')
start_server = websockets.serve(hello, "0.0.0.0", 87, ssl = ssl_context)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()Client:py
import websockets, asyncio, ssl

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain('origin.pem', 'private.pem')

async def hello():
async with websockets.connect("wss://socket.ganer.xyz/gsdgsdfg", ssl = ssl_context) as s:
await s.send("Test")
print("Got data:", await s.recv())

asyncio.get_event_loop().run_until_complete(hello())```
Cloudflare Worker: https://ganer.xyz/s/yQKyhz
Cloudflare Certs [these work for my main website]: https://ganer.xyz/s/iqmjim
Nginx VPS Config: https://ganer.xyz/s/FiGzaK

dense slate
inland oak
wooden ruin
#

what do i need to know in order to consider myself as a "full stack web developer"?

#

it's kind of a vague question now that i think of it but i wanna know the concepts i should know/experience i should have beforehand

inland oak
#

obviously full-stack should know both paths in sufficient manner 😉

#

to reach production state of the product

#

which good code quality, testing, security, scalability and e.t.c.

#

the job of a backend person is quite often touching devops path too though

#

so... full stack I guess should posses skills form all three paths 😉

#

not all of them of course.

#

having good grasp of at least one backend framework (Django, FastAPI and e.t.c.) and one frontend framework (React, Angular, Vue.js) should be enough I think

vestal hound
#

devops, UI/UX, and product management are desirable peripheral skills

wooden ruin
wooden ruin
inland oak
#

never felt like that

vestal hound
inland oak
#

perhaps check devops map there

#

it should bring some more clearity to this path

wooden ruin
vestal hound
cerulean badge
#

can i use uploaded file in a form with FileField with DictReader from csv module ? (context django)

junior spruce
#

Never mind i just duplicated path()

proper current
#

in flask, how do i catch requests going to the "root"? e.g. when i do

@app.route('/', methods=['GET'])
def getCode():
    print(request)

it does not catch when i send a request to http://localhost:8000/ - how can i catch requests that go to the "root" of the webserver?

ivory bolt
#

I mean it should

#

doesn't the server automatically log every request going to the server

ivory bolt
#

anywhere on the page do you have a form

#

that doesn't work

mighty meadow
frail tapir
#

i have a issue when run server in django project . i don't know what is the issue of that . how to solve that . because i am noob in django . then issue is the localhost is not running . instead of that the terminal shows to me a error ,

  File "/home/abc/.local/lib/python3.8/site-packages/django/urls/resolvers.py", line 600, in url_patterns
    iter(patterns)
TypeError: 'module' object is not iterable

The above exception was the direct cause of the following exception:

Traceback (most recent call last):                                   (also lot of file "" blah blah blah )  ```
  


                                                                                                                                                                          my app view.py is 

from django.shortcuts import render
from django.http import HttpResponse

Create your views here.

def index(request):
return HttpResponse('this works') ```

my app > urls.py

from . import views

url_patterns =[
   path("january", views.index)
] my project > urls.py from django.contrib import admin
from django.urls import path ,include

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

#in this code if i comment the path('challenges'.....) it's work properly
#

I think this is simple issue ,.
Also this question is too long .
I don't know how to ask a django doubts ..
Which file should be considered ,😂

Thanks

proper current
proper current
ivory bolt
#

I don't see the problem -- you're visiting the root, the request gets logged

mighty meadow
#

of course the content in terminal also helps.

ivory bolt
#

oh you want to show the request on the page

proper current
#

yes, but how do i actually get the request into the code. because like i said, print(request) does nothing, while it works for other app routes that arent /

ivory bolt
#

gimme a sec

frail tapir
limpid pivot
#

Can any one help me with celery i am stuck in problem of aynchronous task.

I had a problem of timeout error because of taking excessive time by request.(i.e to scrape the site). So I tried with celery to do the scraping task after getting request in views of Django app. This also taking excessive time now. The page is reloading and taking excessive time to run the task. Help me

manic frost
#

Does anybody know why starlette treats functions/methods as (request -> response) functions, and classes like ASGI apps? That seems so arbitrary, why can't a function be an ASGI app?

#

I mean, I can solve this with something like

class sigh:
    def __init__(self, function):
        self.function = function
    
    def __call__(self, scope, receive, send):
        return self.function(scope, receive, send)
``` but why?
native tide
#

guys

#

if i local host my server, the url will be http://<my_ip>:8080/. Can i change it to smth custom? Atleast "erase" the ip

balmy lintel
#

You can customize how it shows up in a browser or client by replacing your ip address with your hostname.

#

What is your goal?

ivory bolt
#

class Sigh:

ivory bolt
#

instead why don't you just use selenium and say wait for element till clickable or something

#

you can do that in selenium

manic frost
opaque rivet
#

😂

manic frost
#

well, yes, the convention is generally to make them in PascalCase

ivory bolt
dusk portal
#

wht im so noob

dusk portal
#

@wooden ruin hey how r u

ivory bolt
#

so if a class has multiple functions that basically work on request --> response logic, then isn't it better to be clled an app

ivory bolt
# manic frost hm?

like in django, I can have a class based view showing different views based on different requests right

#

so let's say you have a complex app

#

so you can manage CRUD operations in different classes

#

maybe maybe not

#

but this is what I think

dusk portal
#
def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    return render(request,'app5/index.html',{'latest_question_list':latest_question_list})``` views.py  why cant i access my this page but i can access the other one Lmao in this its showing my olf HttpResponse and have done ctrl+ s 10000 times
dusk portal
manic frost
#

ASGI is a protocol similar WSGI, but asynchronous.

dusk portal
#

;-;

ivory bolt
manic frost
#

I think you're confusing ASGI apps with class-based views

#

My issues is that Starlette does this when it sees a callable:

  • if it's a function or a (bound) method, it treats it as a request -> response function, not an ASGI app
  • otherwise, it treats it as an ASGI app
#

so I'm asking if there's any particular reason for that, since a function can be an ASGI app as well

mighty meadow
#

is scraping inappropriate? @manic frost

#

Scraping is illegal in some country

opaque rivet
dusk portal
#

oh

#

btw r good at django

#

have a problem 1 more that many ppl tried but noone can help waana try @opaque rivet

opaque rivet
#

sure

dusk portal
#

so i have 3 object

#

and i have fetched them in my home page

#

localhost/detail/1,2,3

#

so as if i wrote there localhost/detail/4

#

it would show an error

#

and i wanted to show it by try expect (method)

ivory bolt
#

I'm pretty sure you can only take one url parameter at a time no

dusk portal
#
def detail(request,question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request,'app5/detail.html',{'question':question})```
ivory bolt
#

show me your url

dusk portal
#

got the things

#

which i wrote up?

ivory bolt
#

yea

#

show me your detail url

#

also did you import Question from models first

dusk portal
edgy kite
#

Can somebody send me a link to the official HTML discord if it exists

dusk portal
#

if u dont mind can i stream it to u @ivory bolt

ivory bolt
#

sure

#

so it's a standard 404

#

or wut

dusk portal
#

add friend @ivory bolt

#

ill show whole issue

#

add friend

opaque rivet
ivory bolt
#

yep

ivory bolt
#

after all it's get_object_or_404

dusk portal
#

but thats why i use this line

opaque rivet
#

So how do you want to handle that error then?

dusk portal
#

question = get_object_or_404(Question, pk=question_id)

#

ofc there is no pk line question id too

#

:lmao:

ivory bolt
#

how do you wanna handle the detailview then

opaque rivet
#

Ok, well that will just raise a Http404 exception.

#

get_object_or_404(Question, pk=question_id)get_object_or_404(Question, pk=question_id) does not actually handle your error, it just raises an exception

dusk portal
#

ok ik that method too u want me to use that?

#

wait a sec

ivory bolt
#

try, except Http404

opaque rivet
# dusk portal wait a sec
def detail(request,question_id):
  try:
      question = get_object_or_404(Question, pk=question_id)
      return render(request,'app5/detail.html',{'question':question})
  except Http404:
      # handle Http404 exception
dusk portal
#

then too

#

its 3 rd day

#

and i code whole day

#

i dont wanna give up

#

but this thing will make me ig

opaque rivet
#

well, that's always gonna render the page even if exceptions are raised, or an error

dusk portal
#

its not

#

thats the issue

opaque rivet
#

is it rendering the debug error page?

dusk portal
#

yes

#

and if i off debug mode

#

it shows error 500

#

internal server error

#

😢

#
Page not found (404)
Request Method:    GET
Request URL:    http://127.0.0.1:8000/detail/5/
Raised by:    app_5.views.detail
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:

admin/
[name='index']
about/ [name='about']
contact/ [name='contact']
posts/ [name='posts']
[name='index']
detail/<int:question_id>/ [name='detail']
The current path, detail/5/, matched the last one.

You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.``` with debug
#
DEBUG = False

ALLOWED_HOSTS = ['*']``` debug off ok?
#
Not Found
The requested resource was not found on this server.```
#

😢

#

@opaque rivet @ivory bolt 😢

opaque rivet
dusk portal
#

bro u god yes u r here ig u can help @wooden ruin

wooden ruin
dusk portal
#

ik

#

but i used expect and try

#

see up ^^^

wooden ruin
#

I know

#

You returned the 404 error in your views.py

#

The code is working as expected

opaque rivet
#

Yeah - where's the 500 error at?

#
Not Found
The requested resource was not found on this server.

This is a 404 error

dusk portal
#

so whats the issue

#

its working?

wooden ruin
#

Everything looks fine

dusk portal
#

LMAO!!!!!!!!!!!

#

i was thinking

#

i was wrong

wooden ruin
#

Have you created any questions?

opaque rivet
#

Yes

dusk portal
#

yes 3

#

they are working yes

opaque rivet
#

It's working correctly

dusk portal
#

x

#

D

#

1 more issue

#

xD

#

my home page still not loading Lmao

opaque rivet
#

If you want it to render a 404 page, you have to make a 404.html page in your templates directory

#

otherwise the 404 exception will return the 404 error message "Not Found". Not sure why you said that was a 500 error.

dusk portal
#

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    return render(request,'app5/index.html',{'latest_question_list':latest_question_list})```views.py ```py
urlpatterns = [
    path('',views.index,name='index'),```urls.py
opaque rivet
#

what's your templates dir look like? (assuming you didn't change where django looks for templates by default)

dusk portal
opaque rivet
#

? So what's your error, the html page is not found?

#

"my home page still not loading Lmao" needs to be a bit more specific

wooden ruin
#

Let me see your file structure and settings.py @dusk portal u gotta be more specific

wooden ruin
dusk portal
#

@wooden ruin

opaque rivet
dusk portal
#

lmao

#

wait lemme correct

#

i just wrote it wrong now

wooden ruin
#

You also are rendering an incomplete html page

#

What about the headers, html and body tags?

dusk portal
#

again my last http response

#

1 sec

molten glen
#

is there anyway to work around the error to return none in flask?
is it possible to just return an empty variable?

dusk portal
#

not working still

manic frost
#

If you get an HTTP request, you must provide some response. That's just how HTTP works.

molten glen
dusk portal
#

same lfmao

molten glen
#

then i want to call the files in my html code

molten glen
dusk portal
manic frost
opaque rivet
#

You can just return a status code if you don't want to return data

manic frost
#

Whatever you want to do, your handler must return a response. If you want an "empty" response, you can return a 200 OK

wooden ruin
#

You must always provide some sort of response. If the client doesn't expect anything, you can return 200

molten glen
#

oh wait i got an idea

dusk portal
#

return pass

#

lfmao

wooden ruin
#

no

#

lol

molten glen
#

i'll just render template my html code

dusk portal
#

only paas

#

pass

opaque rivet
#

no

dusk portal
#

xD

molten glen
#

and not call the variables

opaque rivet
#

🤦‍♂️ yikes

dusk portal
#

wait r u doing flask (my past ) im in django from 2 weeks before that i was doing flask @molten glen

wooden ruin
#

Typically I just return json saying success or failure if all the front-end wants is to send a request and forget about it

wooden ruin
#

Typically the front-end should always follow up on the request

molten glen
#

its mainly for the render templates and python processing of user data

#

i can successfully process user data and return a prediction for data science

#

*score

#

im working on my next features

#

auto analytics

dusk portal
#

lol same

#

i always write render template

#

most of devs say try redirect

#

🤣

molten glen
#

huh

#

then i should just

#

use redirect

#

shoot

wooden ruin
molten glen
#

im feeling so dumb rn

dusk portal
#

but im proud of myself

#

i have done flask with so projects + many efforts

molten glen
#

yep

#

i've been coding for a month in flask

#

now that schools over

dusk portal
#

oh

#

xD

#

im 15 too

molten glen
#

i can do stuff faster

#

cool

dusk portal
#

xD

molten glen
#

yep

#

my neck is practically broken

#

im looking so closely at the flask code

#

thinking the hell is wrong with it

dusk portal
#

ok

#

whats the issue

#

and from where u r learning

molten glen
#

oh im learning by myself

#

learning as i go along

dusk portal
#

i mean

molten glen
#

i think i've solved the issue

dusk portal
#

docs vids yt pluralsight

#

or what

dusk portal
molten glen
#

returning smth

#

i just wasn't thinking

#

i needed to return the html webpage

dusk portal
#

good luck bro

#

ik u will do it

#

and as soon u do it try 1 more project and then django @molten glen

hollow apex
#

Hey guys so, im learning Flask and

#

this is the tab

#

I want this input field to move to the center

#

could u tell me a way

toxic forge
hollow apex
#

I said im a newbie to web okay? I am well formed that Flask is the best point to start from, so, either you help me or pass it

molten glen
molten glen
molten glen
#

welp its just with the files

#

the location

#

so i need to fix it

dusk portal
#

Oh

molten glen
#

i did it on monday

dusk portal
#

U leaning from which resource

molten glen
#

anything there is

barren sable
#

I am working with django on a mysql legacy database. I have integrated everything but passwords. The legacy database is storing the passwords this way
$2a$10$Pdg3h8AVZ6Vl3X1mMKgQDuMriv8iysnValEa5YZO3j9pEboLrOBUK and django reads only if the same hash has the bcrypt$ prefix bcrypt$$2a$10$Pdg3h8AVZ6Vl3X1mMKgQDuMriv8iysnValEa5YZO3j9pEboLrOBUK . How do I make django authenticate users by reading first example hash?

#
PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.BCryptPasswordHasher',
]

#

using this setting now

#

should I create my own password hasher?

twin hamlet
#

Anyone knows about Django here ?

barren sable
twin hamlet
ripe lodge
#

yo quick question, should i learn sql basics before i learn to use sqlalchemy?

empty brook
#

Hi, is someone familiar with fastapi here ?

opaque rivet
#

@ripe lodge I would recommend that. I learnt the ORM before learning SQL and I didn't understand the raw SQL behind the abstraction of the ORM.

ripe lodge
#

thanks! also having a difficult time with that

gritty cloud
#
input {
  display: flex;
  align-items: center;
  justify-content: center;
}
#

this is the easiest way

outer apex
#

Why do you think you have to use JS for scraping a website?

gritty cloud
#

there are plenty of things to use for scraping

#

!pypi scrapy

lavish prismBOT
gritty cloud
#

!pypi selenium

lavish prismBOT
gritty cloud
#

selenium is usually used with beautifulsoup

#

!pypi bs4

lavish prismBOT
ivory bolt
#

the whole idea of django is to use existing libraries

#

@barren sable check out some other password_hashers that you can import with django if there are any

#

otherwise yes you may have to come up with your own

#

bs4 is particularly good for getting data, selenium for interacting with the web pages and testing

#

while flask might be one of the fastest ways to setup everything

#

I suggest you move onto django after you're comfortable with it

#

it's a much more comprehensive framework

languid beacon
#

do anybody know how to create a js file in intelliji ultimate?

ionic raft
#

Thanks for the feedback on text readability. I was contemplating removing the signup link. It's ahead of its time. 🙂

vivid canopy
#

who can help me with django?

ivory bolt
#

I'm here!

ivory bolt
vivid canopy
#

i mb solve but i add u in friends i if i will have provlem i will write

ivory bolt
#

sure! I've sent you a friend request

static vault
#

http://www.who-is-hotter.com/ My friend made this website to help make a data set for an ai, it would be pretty cool if people could help out. It's pretty straightforward.

ivory bolt
#

the ui needs some touch up but it was pretty interesting

#

I assume this is just basic training data

#

nice!

static vault
static vault
ivory bolt
#

Though you may want to tread carefully, even if you're trying to train your model

#

well, your domain is…it could give the wrong idea to the purpose of the site

#

or not

#

you can forget about this

native tide
#

is there any way to send a file from a client to a server in flask?

#

by posting a request

#

like

#

can you send it in the request

#

please ping me when you respond

ivory bolt
#

there is

#

what you're talking about is a basic forn

#

so you send data via a post request

#

I'll let you know how specifically to do that in a sec

ivory bolt
#

can you not store request as an instance

#

so, if I have request, I can store it as the following:
home_request = request

#

or something like that

vivid canopy
#

@ivory bolt can u help?

#

who can help with django

#

?

thorn igloo
#

man, you could've just posted your question

limpid pivot
ivory bolt
ivory bolt
cerulean badge
#

in what unit do i need to pass the file size in multiple_chunks method of the File objects (context django)

#

bytes?

coral raven
#

read the docs

#

Does extending the User model affect the PasswordChangeView, PasswordResetView in anyway. If yes, what changes should be done?

scenic dove
#

this

vivid canopy
#

how i can redirect login page into home page

dusk portal
#

a href op

dusk totem
vivid canopy
dusk totem
#

... you don't check if the credentials are correct?

vivid canopy
#

ca u write a code how it's must look

coral raven
#

LOGIN_REDIRECT_URL = 'blog-home' redirect to the name attribute you added in the views.py file to your home view

vivid canopy
#

same situation

#

what i should do?

tidal dock
#

anybody can help me

#

which frontend will be good with flask?

native tide
#

could anyone explain why we would want to use dead link using has symbol because im kinda confused why you would you use it and how it works?

hidden crown
#

Hi peoples!
I have a question about a scalable django solution:

  • The setup: one Postgresql server and multiple (7ish) docker containers running the django application
  • The challenge: periodic tasks & long running tasks which I need to decouple from http requests
  • Current fix: Both are now triggered by some http requests, but make loading times terribly long on these requests.
  • Current fix bis: Scheduled tasks (cron wise) are triggered mulitple times (once in each docker instance of the django app)
  • Way forward: Celery looks like the good way to go, but I cant understand how i can handle the multiplication issue (We dont want tasks being triggered 7 times, once by each container)

Idea's, experiences & suggestions?
Thanks!

hidden crown
# tidal dock which frontend will be good with flask?

Simple templating can be done with jinja, works quite good. Some ajax interaction can quickly be added with jquery. If you want to go even further and have more development capabilities in the frontend, React is also a good way forward. There is ofcourse a learning curve (which I'm currently travelling on).

hidden crown
# tidal dock which frontend will be good with flask?

https://developer.okta.com/blog/2018/12/20/crud-app-with-python-flask-react is a nice flask+react tutorial.
Link comes from https://www.fullstackpython.com/react.html which have quite some links to useful resources.

Okta Developer

Create a CRUD (create, read, update, and delete) application using Python, Flask, and React.

ivory bolt
vapid gulch
#

Hey everyone,
We would like to present to you our Project KLASI, a Smart Virtual Classroom that provides futuristic tools and resources that aims to a successful e-learning and teaching experience in a modern way. This project is a web based application made using mainly the MERN stack development, different libraries and external apis.
To sum up, our project does not end at this point, we are still working to further our approach, It is easy to imagine the improvement and impact of it with a range of upgrades and other more advanced functionalities on the education field. Hoping to reach all of you , Please support us with some likes. 💪🏻🙏🏻💙 https://lnkd.in/d9kumXc

Pour rencontrer l'équipe KLASI et en savoir plus sur ce projet, RDV le 10 Juin 2021 entre 11h et 14h en suivant ce lien : https://meet.google.com/jyu-hfjk-xq...

▶ Play video
ivory bolt
ivory bolt
ivory bolt
dusk portal
#

cez i was thinking

#

it was my bad

#

then my pc trash

#

then browser

#

and then i though vs code and then pip unistall django and install it

#

debug on off try expect get_object_or404

#

done all

#

@ivory bolt the page 4 of docs is hard bruh

#

its my 12th day on django

#

less go

hollow apex
#

Hey so

#

I changed the colour with css

#

but then I could delete or change to another colour\

#

its stuck on this blue one

#

oh I just did it

#

nvm

hidden crown
hollow apex
#

yes yes

#

that was the issue

#

wait wait

#

can you tell me how can I clear the cache?

hidden crown
hollow apex
#
<link rel="stylesheet" type ='text/css' href="{{ url_for('static', filename = 'style.css') }}">
#

I removed this but

hidden crown
#

Which browser do you use?

hollow apex
#

chrome

hidden crown
#

first you can rightclick and click inspect... to check the source in your browser

hollow apex
#

yes

hidden crown
#

There in the network tab there's a checkbox "Disable cache"

hollow apex
#

I have checked that box

#

honestly, I did that yesterday

hidden crown
#

normally when refre

#

He doesnt save it, i think

#

so when starting to dev, i select it & keep the debug window open

hollow apex
#

here is the style.css cached

hidden crown
#

link to the file doesnt work it seems, the file is marked red

hollow apex
#

yes cuz I deleted that

#

wanted to clear everything cuz I could not do anything to clear xd

hidden crown
#

The reference to the file in your template too?

hollow apex
#

when I delete the reference, it works

hidden crown
#

Something still goes looking for style.css

#

aparently the "caching disables" remains until you close the Developer Tools window

hollow apex
#

all has been done

#

thank you

dusk portal
#

how may i help ,did u resolved the issue or may i help @hollow apex

#

meanwhile me:what's that

coral raven
#

all you need is a ctrl+shift+r to hard reset your webpages

opaque rivet
#

@hidden crown instead of running celery on each django container, maybe just make a separate container with celery to handle all the periodic tasks? That way you're not duplicating tasks.

subtle otter
#

hii , so i'm trying to use sqlite3 db with flask but i keep getting this error sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 4228 and this is thread id 10756. , and as i googled i found out that the problem is the connection must be in the same thread as the cursour . but i'm using the cursor in two functions that are outside of the app.route() , how do i return the cursor so i can use it in those functions pls?

#

this is one of those two function

def insert_ws(ws):
    with conn:
        c.execute("INSERT INTO MD5 VALUES (?, ?, ?, ?, ?)", (ws.md5, ws.link, ws.language, ws.type, ws.date))
#

don't mind my question i fixed it

opaque rivet
#

What do you guys use to host your docker containers

mighty meadow
hidden crown
#

@opaque rivet The mentioned ones are just the latest ones used by me. DO has like 5 USD/month servers with only the proportion used to be payed, so that's what I often use to try things out (when it's short term it costs like a few cents). This will be similar in other projects. You can also just run it locally (I use a ubuntu desktop PC to run these things, also tried it using Windows Sublayer for Linux (WSL). if u want to share a locally running project: https://ngrok.com/ is quite fun to use

pine trellis
opaque rivet
#

@hidden crown awesome thanks. I still have yet to deploy anything, i was hoping to learn nginx and then aws. You seem very knowledgable!

hidden crown
hidden crown
# opaque rivet <@696423463136788501> awesome thanks. I still have yet to deploy anything, i was...

Same with docker containers: there are useful docker images having everything setup already, like https://hub.docker.com/_/django
Try to go for official docker images or images from trusted parties as they are more reliable and are safer is you're not quite into how to get everything running safe and well (and even if safety is your expertise, maintenance & reliability will always be better from bigger, known parties)

inland oak
# opaque rivet What do you guys use to host your docker containers

?tag largehosting (from https://discord.gg/code)

Free:

Paid:

  • Azure https://azure.microsoft.com/en-us/
    Starting at $1.69/month for their B1LS virtual machines, 0.5GB of ram and 4GiB of SSD storage.
  • OVH: https://www.ovh.com/us/vps/
    Full VPS starting at $3.49USD/month, choice of OS, high reliability.
  • Digital Ocean: https://m.do.co/
    Starting at $5/month (USD), you can have your own server with 20GB SSD Disk, and 512MB Memory. Use https://bithost.io/ if you want to pay with cryptocurrencies.
  • Linode: https://www.linode.com/
    Starting at $5/month (USD), you can have a server with 20GB SSD Disk, and 1GB memory
  • Vultr: https://www.vultr.com/
    Starting at $2.5/month (USD), you can have a server with 20GB SSD Disk, and 512MB Memory
  • Amazon(AWS) Lightsail: https://amazonlightsail.com/
    Starting at $5/month (USD) (first month free), you can have your own server with 20GB SSD Disk, and 512MB Memory.
  • VIRMACH: http://virmach.com/
    Full Windows and Linux Desktop VPS starting at $7USD/month and $10USD/month respectively.
  • Sloppy: https://sloppy.io/
    Starting at 5$/month (USD) You can have 500MB Memory, 1TB Transfer per month and 16GB of storage. Extra
    storage and ram can be bought.
  • Galaxygate https://www.galaxygate.net/
    Starting at 3$/month (USD), get 15GB of storage, 1GB of ram, and unmetered bandwidth.
  • Hetzner https://www.hetzner.com/cloud
    Starting at 2.49€/month (EUR) for 20GB of storage, 2GB of ram and 20TB of traffic.
subtle otter
#

hello , is there a way to make an html progress bar for a script??

#

got this script that's running in teh background and takes sometime to finish , i want to make the progress bar to indicate welp the progress of the script

native tide
ivory bolt
austere relic
rapid spindle
#

Hello, I have a bad request with django when I try to log on with angular. Is Anyone know how to fixe it?

native tide
#

https://paste.pythondiscord.com/iyarikegam.py - server.py
https://paste.pythondiscord.com/aqekuwitot.rb - client.py
I created a chat of an unlimited number of people using threads and sockets.
In server.py I created 2 lists the first one contains the names the customers chose for themselves and the second one contains the customer details like port and the rest.
Later, I created several functions, the first of which is called broadcast receives a message and sends it in a chat with the name of the person who sent it.
The second one named CaesarEncrypt encrypts the message (it is unrelated).
The third named HandleClient requests a message from the client and sends it to broadcast, if the message is not received it deletes the client's details from the 2 lists and closes the client.
The fourth named recive receives the client for the first time and adds its details to the lists and of course prints a message that a new client has connected to the server.
In client.py I did all the construction of the chat using Tkinter and it works fine as usual.
Now what I want to do is create a chat manager that will work like everyone else on the server but when he enters the command /admin 5270 for example then it will buy him manager capabilities and he will be able to take people out when he writes /kick and the client name next and it will close that chat And will be registered in the chat "The client (name) has been removed from the server".

opaque rivet
#

@native tide i disagree

tepid lark
#

bit of a long shot, but does anyone have experience with shibboleth sp 3?

sonic island
dusk portal
sonic island
dusk portal
#
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse

from .models import Choice, Question
# ...
def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))```
#

This is damn hard

dusk portal
civic pewter
#

is it possible to provide links from the stack .. ?

#

I wanted to know how I can save a photo that will contain a watermark. Currently grabs a photo from the form and creates a watermark on it, but saves it separately. More precisely, I would like the photo I send in the form to be processed and saved.

hollow apex
#

hello so, my problem is following:

#

this is the page I have made so far

#
from flask import Flask,render_template,request
from random import randint
app = Flask(__name__)


  
                        
@app.route('/random')
def random_page():
    return render_template('random.html',the_title = 'Random Generator')




if __name__ == "__main__":
    app.run(debug=True)
``` this is the flask code
#
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

    <title>{{ the_title }}</title>
    <link rel="stylesheet" type ='text/css' href="{{ url_for('static', filename = 'style.css') }}">
</head>
<body>
    {% block content %}
    {% endblock %}
</body>
</html>
``` this the base html code
#
{% extends 'base.html' %}
{% block content %}
<div class="random-page"> 
    <form method="POST" action="search">
        <table>
            <h1>Random Number Generator</h1>
            <tr>
                <td>Min:</p>
                <td><input type="number" name="range_start" width="30"></td>
                
            </tr>
            <tr>
                <td>Max:</td>
                <td><input type="number" name="range_end" width="30"></td>
            </tr>
        </table>
        <p><input value="Generate" type="SUBMIT"></p>
        <h1>{{ the_result }}</h1>
    </form>
</div>
{% endblock %}``` and this is the code of the page I have shown you
#

so according to the screen, I want to make a random number generator, the problem is that when I try to do so, I get an error which I don't understand at all

#

so in order to grab the value of the input, I did following

#

@app.route('/random',methods = ['POST'])
def random_page():
    range_start = request.form['range_start']
    range_end = request.form['range_end']

    result = randint(range_start,range_end)
    return render_template('random.html',the_title = 'Random Generator',the_result = result)
#

after the implementing of this code, I get this

#

ik its a lot of code but it was just for clarity, overall its not a big problem, I just don't know where I make the mistake

hollow apex
rigid prairie
#

Hey

#

would u guys recomm me django courses

civic pewter
#
    if request.method == 'POST':
        form_w = ImageForm(request.POST, request.FILES)
        if form_w.is_valid():
            # form = form_w.save(commit=False)

            cd = form_w.cleaned_data['img']


            im = Image.open(cd)
            width, height = im.size

            draw = ImageDraw.Draw(im)
            text = "TEST WATERMARK"

            font = ImageFont.truetype('arial.ttf', 36)
            textwidth, textheight = draw.textsize(text, font)

            # calculate the x,y coordinates of the text
            margin = 10
            x = width - textwidth - margin
            y = height - textheight - margin

            # draw watermark in the bottom right corner
            draw.text((x, y), text, font=font)

            print('Before saving: ', im)

            im.save('Luki/media/upload_p/{}'.format(cd))

            img = Image.open(('Luki/media/upload_p/{}'.format(cd)))
            print('After saving: ', img)

            form_w.instance.save()

            return redirect('Luki:gallery')
    else:
        form = ImageForm()
    return render(request, 'Luki/upload_img.html', {
        'form': form,
    })```
#

I wanted to know how I can save a photo that will contain a watermark. Currently grabs a photo from the form and creates a watermark on it, but saves it separately. More precisely, I would like the photo I send in the form to be processed and saved.

austere relic
#

Check if it exists

#

if it does, remove it

#

You know JS?

ivory bolt
#

wait, just try to restart the flask server

#

It should work otherwise

hollow apex
#

I have a headache already man xd idk what is wrong to fix

ivory bolt
#

just restart

#

maybe because you made the change and saved, but it's still running on that first one

#

tell me if it works

#

I'll check it out

hollow apex
#
from flask import Flask,render_template,request
from random import randint
app = Flask(__name__)


@app.route('/home')
@app.route('/')
def home_page():
    return render_template('home.html',the_title = 'Home')



@app.route('/random',methods = ['POST'])
def random_page():
    range_start = request.form['start']
    range_end = request.form['end']

    result = randint(range_start,range_end)
    return render_template('random.html',the_title = 'Random Generator',the_result = result)


if __name__ == "__main__":
    app.run(debug=True)
#
{% extends 'base.html' %}
{% block content %}
<div class="random-page"> 
    <form method="POST" action="random">
        <table>
            <h1>Random Number Generator</h1>
            <tr>
                <td>Min:</p>
                <td><input type="number" name="start" width="30"></td>
                
            </tr>
            <tr>
                <td>Max:</td>
                <td><input type="number" name="end" width="30"></td>
            </tr>
        </table>
        <p><input value="Generate" type="submit"></p>
        <h1>{{ the_result }}</h1>
    </form>
</div>
{% endblock %}```
#

motherfckers, advertise the websites and then run away

ivory bolt
ivory bolt
#

what if you change the action to "."

hollow apex
ivory bolt
#

I get what you're doing that's a fact

#

wait lemme try

hollow apex
#

I tried but with that I get another error

ivory bolt
#

what was that

hollow apex
#

full image

ivory bolt
#

so wait lemme try

hollow apex
#

okay, id be greatful

#

okay and what should I change in the html action?

ivory bolt
#

method should remain post, change action to "."

#

I'm still trying one sec

hollow apex
languid beacon
#

no

hollow apex
#

I tried printing the request.form if it helps to help me , lol

ivory bolt
#

k so I think this is where you're going wrong

#

range_start = request.form['start']

#

let's start from here

hollow apex
#

okay lets start

#

should name not be in request.form[name] ?

ocean tide
#

Hey, i'm trying to use border-radius on an image and it will only round the bottom left and right corners and not the top left or right... Anyone know what could be causing this?

ivory bolt
hollow apex
#

I cheched

#

I tried the following now

#
from flask import Flask,render_template,request
from random import randint
app = Flask(__name__)


@app.route('/home')
@app.route('/')
def home_page():
    return render_template('home.html',the_title = 'Home')
                        


@app.route('/random',methods = ['GET','POST'])
def random_page():
    range_start = request.form.get('start')
    range_end = request.form.get('end')

    result = randint(range_start,range_end)
    return render_template('random.html',the_title = 'Random Generator',the_result = result)


if __name__ == "__main__":
    app.run(debug=True)
#
{% extends 'base.html' %}
{% block content %}
<div class="random-page"> 
    <form method="POST" action="{{ url_for('random_page')}}">
        <table>
            <h1>Random Number Generator</h1>
            <tr>
                <td>Min:</p>
                <td><input type="number" name="start" width="30"></td>
                
            </tr>
            <tr>
                <td>Max:</td>
                <td><input type="number" name="end" width="30"></td>
            </tr>
        </table>
        <p><input value="Generate" type="submit"></p>
        <h1>{{ the_result }}</h1>
    </form>
</div>
{% endblock %}
#

I saw it on herehttps://www.geeksforgeeks.org/retrieving-html-from-data-using-flask/

#

but I think it returns none, see

#

@ivory bolt

ivory bolt
#

hey

#

I checked something

hollow apex
#

wut

ivory bolt
#

I also came to a type error

#

first, I changed it to:
if request.method == "POST":

#

and put something for get

#

so you shouldn't get an invalid method

hollow apex
#

like this, right

#

yes I did as well

#

As I said

#

it returns none