#web-development

2 messages · Page 210 of 1

uneven plume
#

I thought the token would be found in /show_token endpoint

native tide
#

what should i do after htmland css for web development

junior wraith
#

fastapi is working with pydantic very closely, I recommend using it when working with fastapi

uneven plume
#

when I get redirected from callback the token should appear?

junior wraith
#

I changed the value of a token to None

async def show_token(
        request: Request,
        token: str = None
):
#

just to test the code

#

change it to the original value - idk what it was

uneven plume
#

oh

#

it worked!

#

thx alot 😄 now I can move to next step on my chatapp!

junior wraith
uneven plume
fallow cairnBOT
#
In the future, don't do that.

@uneven plume, please enable your DMs to receive the bookmark.

junior wraith
uneven plume
serene prawn
#

FastAPI uses pydantic internally afaik

uneven plume
#

Interesting, that's good to keep in mind

#

thx a lot!

junior wraith
serene prawn
#

Yep, just checked, it requires starlette and pydantic

#

It uses pydantic for schema generation and data validation

zealous jasper
#

hello, I am unable to login to django admin panel using custom user model that I created

#
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.hashers import make_password
from phonenumber_field.modelfields import PhoneNumberField


class UserAccountManager(BaseUserManager):
    def create_user(self, email, username, first_name, last_name, phone, password=None):
        if not email:
            return ValueError("User must have an email address!")
        if not username:
            return ValueError("User must have a username!")
        if not first_name:
            return ValueError("User must have a first name!")
        if not last_name:
            return ValueError("User must have a last name!")
        if not phone:
            return ValueError("User must have a phone number!")

        user = self.model(
            email=self.normalize_email(email),
            username=username,
            first_name=first_name,
            last_name=last_name,
            phone=phone,
        )
        hashed_password = make_password(password)
        user.set_password(hashed_password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, username, first_name, last_name, phone, password):
        user = self.create_user(
            email=self.normalize_email(email),
            username=username,
            first_name=first_name,
            last_name=last_name,
            phone=phone,
            password=password,
        )
        user.is_admin = True
        user.is_staff = True
        user.is_superuser = True
        user.save(using=self._db)
        return user
#
class UserAccount(AbstractUser):
    username = models.CharField(null=False, blank=False, max_length=30, unique=True)
    first_name = models.CharField(null=False, blank=False, max_length=50)
    last_name = models.CharField(null=False, blank=False, max_length=50)
    email = models.EmailField(null=False, blank=False, unique=True)
    date_joined = models.DateTimeField(auto_now_add=True)
    last_login = models.DateTimeField(auto_now=True)
    phone = PhoneNumberField(unique=True, null=False, blank=False, max_length=13)
    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)

    USERNAME_FIELD = "username"
    REQUIRED_FIELDS = ['first_name', 'last_name', 'email', 'phone']

    objects = UserAccountManager()

    def __str__(self):
        return str(self.username)

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True
native tide
#

so which result on google are you not too sure about?

supple fossil
#

How can I debug mod_wsgi? I think I have it configured correctly, but my Flask app keeps giving 404

#

The apache error.log file says "file does not exist" for me, and gives /var/www/html/myapp which makes me figure that mod_wsgi isn't mapping the requested URL to my app.

#

But I can't se anything wrong in my WSGI configuration.

tender moat
#

Hi guys, I'm trying to deploy a website using Heroku. Heroku is connected to github and any pushes I make to github will update the website. I am a bit confused how to make my environmental variables private?

#

These are the variables that I get using os.getenv()

#

and make private on my own computer

frank shoal
#

don't share your computer and they become private.

#

Though you shouldn't be using prod instances locally.

tender moat
#

i see but i guess I don't quite understand how the website can use them if I'm not hosting the website on my computer but on the cloud

#

using heroku

frank shoal
#

you would configure them using the heroku command or via the web interface

tender moat
#

ohhhhh that makes sense

#

thank you!

dark night
#

Ive noticed the PokeAPI serializes their response to make it easier to read, how can I learn to do that? Is that a result of how they query their database or is it down through your own code?

frank shoal
#

What do you mean by serialize?

#

pretty printing?

quick cargo
#

generally you dont want to pretty print the responses themselves

#

most browsers and api clients for testing will pretty print it automatically

dark night
quick cargo
#

but also the user's responsibility to pretty print if they want.

#

otherwise you're just gonna be needlessly increasing the response size

dark night
#

I dont think thats what I meant actually. https://pokeapi.co/ In this example, their API returns a lot of data on ditto, but its further grouped by abilities, game indices, held_items, etc

serene prawn
#

You can return related entities if you're talking about that

mystic wyvern
# zealous jasper ```Python from django.contrib.auth.base_user import AbstractBaseUser, BaseUserMa...

in

    def create_superuser(self, email, username, first_name, last_name, phone, password):
        user = self.create_user(
            email=self.normalize_email(email),
            username=username,
            first_name=first_name,
            last_name=last_name,
            phone=phone,
            password=password,
        )
        user.is_admin = True
        user.is_staff = True
        user.is_superuser = True
        user.save(using=self._db)
        return user

do this


    def create_superuser(self, email, username, first_name, last_name, phone, password):
        user = self.create_user(
            email=self.normalize_email(email),
            username=username,
            first_name=first_name,
            last_name=last_name,
            phone=phone,
            password=password,
        )
        user.admin = True
        user.taff = True
        user.superuser = True
        user.save(using=self._db)
        return user
dark night
#

how can I post code in the chat?

native tide
#

@dark night You can use the ` character

bitter spindle
#

Have anyone ever tried to access external APIs from django migration file? And did it work as well?

dark night
#

Ill just share a link so I dont flood the chat. https://codeshare.io/LwZM37 currently, the response from the API i'm creating is the top example, but I would like to make it look like the bottom example. How can I learn to do this?

serene prawn
#

What if api changes? What if it's unavailable?

#

Migrations should run and rollback regardless

bitter spindle
#

yes that's right

cerulean badge
#

anyone has done token authentication in drf with mandatory email confirmation + password rest etc?

hollow verge
#

I have flask app and I have setted up nginx with it
When I use ip in my browser uri I get my website but when I use domain I dont get my website what is issue?

#
server {
    listen 80;
    server_name scrupa.com www.scrupa.com;

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/dhairya/PD2/myproject.sock;
    }
}
#

this is my configuration

simple phoenix
#

It has a pointer typically to the current node or location in the stream

#

Nowadays we serialize to JSON too

#

Much more typical in a Web context although XML, CSV, TSV, Word, Excel i have seen too in prod web code

simple phoenix
#

You can write your own serializer methods or classes to formats if you need to but you need an in depth knowledge of the formats to ensure it works.

tough heart
onyx pivot
#

I am having a problem with django
It says module <app>. Urls not found

#

can anyone help me?

crude stirrup
#

how should I put this in the middle and be responsive?

#
<section id="panels">
        <a href="{{ url_for('intro') }}" class="panel">
          <h2>Introduction</h2>
          <p>New to hata? Here we have introduction about hata!</p>
        </a>
        <a href="{{ url_for('topic') }}" class="panel">
          <h2>Topic</h2>
          <p>Don't have any idea? Take a peek here and see topics</p>
        </a>
        <a href="{{ url_for('ref') }}" class="panel">
          <h2>References</h2>
          <p>Need references? Jump right in to see other references!</p>
        </a>
        <a href="{{ url_for('meta') }}" class="panel">
          <h2>Meta</h2>
          <p>Want to know more about project? Lez Go!</p>
        </a>
      </section>```
#
/* PANELS */
#panels {
  align-items: center;
}

#panels .panel {
  background-color: lightgrey;
  border-radius:6.9px;
  box-sizing: border-box;
  color: black;
  display: inline-block;
  margin: 6.9px;
  padding: 20px;
  text-align: center;
  text-decoration: none;
  width: 269px;
}```
mental summit
crude stirrup
#

Flex container?

#

Btw I'm kida new to html css

mental summit
#

So like add display: flex;

#
crude stirrup
#

In #panels or .panel?

#

Ey it kinda worked

mental summit
#

#panels

crude stirrup
#

But it's kinda weird

#

I only want 2 boxes in normal view thinkmon

mental summit
#

Maybe just add margin: auto; to the #panels element and remove the display: flex and align-items: center

crude stirrup
#

welp it came back to the original state

crude stirrup
brazen ravine
#

is this the right channel to ask about aiohttp? or is there a better one

#

maybe #async-and-concurrency ? But it's not really a question about async and concurrency, it's about the library itself

mental summit
# crude stirrup this

Maybe add display: grid; and align-content: center; to #panels and remove the margin

crude stirrup
mental summit
#

Bruh

crude stirrup
#

this kinda works but I want it two by two thinkmon

#

css is peyn

mental summit
#

What is #panels parent?

crude stirrup
#

nothing

mental summit
#

So.. the body tag?

crude stirrup
#

but add the few lines I added above

mental summit
#

Maybe add width: fit-content; and margin: auto; to #panels and remove the existing css declarations there

crude stirrup
#

pog

mental summit
#

Remove the display grid and align-content center

crude stirrup
#

done it's still the same

#

never mind

#

but now it's like this

mental summit
#

-_- bruh

#

Maybe add

display: grid;
grid-template-columns:  auto auto;
align-content: center;
crude stirrup
#

it worked !

#

but

#

@mental summit how do I fix that one above

mental summit
#

You’d need to change the size of the content

#

Wait

#

was there horizontal scrolling

crude stirrup
#

no?

mental summit
#

What I meant is that did you zoom out and take the screenshot

crude stirrup
#

Nope

mental summit
#

Maybe you need to set the navbar width to 100vw

crude stirrup
#

Navbar? yert

mental summit
#

Idk it looked like the navbar was smaller

#

And you said that you didn’t zoom out

radiant aurora
#

Hey guys, can anyone tell me how do I return two variables using HTTPResponse in Django? The below is working:

return HttpResponse("Secret Key: %s" %secret_key)

But, this is not working:

return HttpResponse("Secret Key: %s" %secret_key, "ABC: %s" %sc)
crude stirrup
#

@mental summit oh actually

#

it is

#

I actually zzoomed

mental summit
#

In that case you’d need to change the size of the content in some way

crude stirrup
delicate crane
#

@radiant aurora pack them in a dict

#

But this is a python web dev channel

mossy bane
glossy cloak
#

ask me questions about HTML & CSS

#

i can help

native tide
#

@trim isle dm

trim isle
gaunt heath
#

guys, im trying to set up a phpmyadmin on debian , the page loads, but is blank

#

the sourcecode is there, but it simply doesnt display anything

native tide
#

Re-posting here because the main help channel is very busy:

I want to parse "normal" text to HTML, which library or approach can I use? Basically I have just text delimited by line breaks and I want to surround every paragraph with HTML <p></p> tags. Only paragraphs, no headings or other data

inland oak
wild cedar
#

When I try to run the finished product I made from this tutorial "Python Website Full Tutorial - Flask, Authentication, Databases & More"
I get a blank homepage, I only see the upper menu.
Any help figuring out why I see the notes(home) page empty?

wild cedar
#
{% extends "base.html" %} {% block title %}Home{% endblock %} {% block content %}
  <h1 align="center">Notes</h1>
  <ul class="list-group list-group-flush" id="notes">
    {% for note in user.notes %}
    <li class="list-group-item">
      {{ note.data }}
      <button type="button" class="close" onClick="deleteNote({ note,id })">
        <span aria-hidden="true">&times;</span>
      </button>
    </li>
    {% endfor %}
  </ul>
  <form method="POST">
    <textarea name="note" id="note" class="form-control"></textarea>
    <br />
    <div align="center">
      <button type="submit" class="btn btn-primary">Add Note</button>
    </div>
  </form>
  {% endblock %}```
this is the code itself for the home page in HTML, which shows up blank.
dim plume
#

Hello

#

Is there any services where i can host my fastapi server?

inland oak
inland oak
#

if u wish free ones... there are options too

dim plume
#

i need a free one

inland oak
#

Digital Ocean, Vultr, Linode, AWS, Google, Azure
all provide free servers during first try-period time

#

all for different time limits though

#

Digital Ocean 100$ for 60 days

#

Google 300$ for 3 months / + some servers for 6+ months

dim plume
#

won't it require a cc?

wild cedar
inland oak
inland oak
dim plume
inland oak
#

some providers accept PayPal

dim plume
#

Anything else except heroku?

inland oak
#

For free and without security check by cc... I don't know.

#

raise your own server then 😉

#

as long as u can have public IP from your ISP

dim plume
#

oh

native tide
keen nimbus
#

hi

#

can i make web page using python?

#

i am new tp pything

#

i mean

#

python

inland oak
keen nimbus
#

can u help me?

austere skiff
hazy bone
#

I am testing a simple python socket server where i need to pass files content to the client, and the client can request a file by entering it in the url such as : localhost:8080/nicefile.txt and then i would send that file to them so they can view it in the browser. However how can i parse the url (localhost:8080/nicefile.txt) that they entered so i know which file to send?

quick cargo
#

my advise is use a HTTP server and framework like Gunicorn + Flask

#

doing it with your own raw socket server is a bad idea

hazy bone
hazy bone
# keen nimbus umm.....what?

a client can go onto the localhost server and enter a file such a nicefile.txt in the parameters then i would like to know how to retrieve/print the filename they entered

quick cargo
#

you're going to be writing your own HTTP web server

#

which I dont advise doing

hazy bone
quick cargo
#

alr, well for starters forget about serving the file

#

first step is writing the HTTP server itself

hazy bone
#
host = ''
port = 8080
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))
sock.listen(5) 


while True:
    csock, caddr = sock.accept()
    print("Connection from: " + str(caddr))
    req = csock.recv(1024) 

    csock.close()


This simple web server, how would i get the incoming data such as the parameters?

quick cargo
#

thats not a simple web server

#

that is a basic socket,

hazy bone
#

web socket then

quick cargo
#

you'll need to implement the following for it to be a web server and compatible with browsers

  • Flow control
  • HTTP/1 Spec parsing
  • Body streaming and request parsing / feedback
quick cargo
hazy bone
quick cargo
#

you want to serve a file to the browser right?

hazy bone
#

I  must implement a web server that is capable of serving files from a lo- cal folder. This means that you are only required to implement the HTTP GET method, but you may want to implement the HEAD method as well, as it may be useful for testing. The server should be able to run indefinately, by which it is meant that it should not just process a given number of response and then stop.
The server should work as a plain file server and should accept a path to a folder and a port number. The server may also take an address to listen on, but if this is not implemented, the server should listen on all addresses on the port specified. Files and folders in specified path should be served up by the webserver. If a folder on the server is accessed (with a URL ending in a /) then you should serve up the contents of file named index.html, if one exists, or a listing of the files and folders, if index.html does not exist.

quick cargo
#

h11 is your friend

hazy bone
#

i cant use other libraries or external modules but your saying i should look at the code of h11?

quick cargo
#

you could do an incredibly basic / incorrect web server by just hard coding values and making some broad assumptions about the data you're receiving

hazy bone
#

i think thats fine

quick cargo
#

which, yes, is a bit more simple just reading like 1KB and just hoping it contains everything

#

however if it's gotta to actually be a correct web server then you're looking at a few thousand LOC

keen nimbus
merry tide
#

if starting with Django what is the best doc without the default one?

warped aurora
#

Is it a problem to have different ajax requests in the same script file?

inland oak
warped aurora
# inland oak The code is code (At least in programming languages with standard logic). Separa...

ok cool. I've got two different ajax calls that should execute on different button clicks but I'm having a problem handling them in flask. Both calls post to the same route and I thought I could handle it by doing this

def process():
    if request.method == 'POST' and request.form['call1']:
        do something

   if request.method == 'POST' and request.form['call2']:
        do something```
But I'm getting a bad key error 'call1' when I click the button that should post call 2
inland oak
#

secondly, checking in python key existence by boollean request.form['call1'] should be not correct

warped aurora
#

ah should be something like 'call2' in request.form right?

inland oak
inland oak
#

request.form['call1'] will just raise an KeyError i think, if call1 is not existing

#

request.form.get("call1") can extract without raising errors (it should return "" if not existing)

#

request.form.get("call1", Your_default_value) or you can point explicitely what whouls be returned if not found

finite laurel
#

Hey guys, Im making an app which takes input from user's camera. So I am using opencv and face recognition. The app is working fine, the problem lies with deployment. Does anybody have any idea regarding deploying opencv camera based applications?? If so, pls do help

finite laurel
#

I am using a Flask based web server to capture the user's image from a live video stream form the user's camera. I need help in connecting with the user's camera. Locally I would have used cv2.VideoCapture(0), but this is not the case when it's deployed, so can anybody help with this and to deploy it.

warm iris
#

import jwt
from django.db import models
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin

from cores.models import TimestampedModel

class UserManager(BaseUserManager):
def create_user(self, username, email, password):
if not username:
raise TypeError('User must have a username.')
if not email:
raise TypeError('Users must have an email address.')

    user = self.model(username,
                      email=self.normalize_email(email))
    user.set_password(password)
    user.save

    return user

def create_superuser(self, username, email, password=None):
    if password is None:
        raise TypeError('Superusers must have a password.')
    user = self.create_user(username, email, password)
    user.is_superuser = True
    user.is_staff = True
    user.save()
    return user

class User(AbstractBaseUser, PermissionsMixin, TimestampedModel):

username = models.CharField(db_index=True, max_length=255, unique=True)

email = models.EmailField(db_index=True, unique=True)

is_active = models.BooleanField(default=True)

is_staff = models.BooleanField(default=False)

# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case we want it to be the email field.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']

# Tells Django that the UserManager class defined above should manage
# objects of this type.
objects = UserManager()

def __str__(self):
    """
    Returns a string representation of this `User`.

    This string is used when a `User` is printed in the console.
    """
    return self.email
#

please guys i need help the create_user and create_superuser returns: TypeError: create_user() missing 2 required positional arguments: 'email'

royal musk
#
class Product(models.Model):
    name = models.CharField(max_length=1024)
    count = models.IntegerField(default=1)

    def __str__(self):
        return self.name

Do you know, why terminal doesn't return a object without name istead name of the object? Help, guys

#

object has included name in its attributes.

frank shoal
#

That's what Product's __repr__ method returns.

#

Wrap it in str()

royal musk
#

in str? how? str(Product.objects.get(id=1)) ?

#

@frank shoal

woeful mica
#

Hey, does someone know a python library for web push notifications? Creating the vapid keys (private & public) & sending the notification to a browser using the keys? Tag me if you know

royal musk
#

okay, I try it

#
>>> str(Product.objects.get(id=1)) 
'Product object (1)'
#

I wanted to get this form:

#
>>> str(Product.objects.get(id=1)) 
<Product: python_keychain>
real edge
#

Hey, I am wondering, how to add python plotly to website

royal musk
regal sandal
#

Hey guys!!

I'm looking for some REST API challenge to study!!
Like building some CRUD API...
Does anyone know some?

real edge
native tide
#

Does anyone know if django's loaddata command wipes the database before loading the fixtures?

I did a run just a while ago and I noticed that my data on AWS RDS is already gone. The command is still loading the fixtures though I can't see anything from my app's models in the database except the built in stuff

finite laurel
thick sinew
#

How do I remove these messages?

#

it's django admin panel

stark tartan
#

how can we pass multiple images from React axios and Django rest framework

unreal narwhal
#

Hello how do I turn this public key to PEM format?

{'kty': 'RSA', 'e': 'AQAB', 'kid': 'e49b9f971574455ba969b20697a2c7b6', 'alg': 'RS256', 'n': 'rEFxuU7IZiiKzyjVQ9U3yW594Hll-jjuWK-vYZBC9JZ4FmWMSsG3auvkpieUjrkMKKEP5YSLbhOOzjcRPRxSEcDfJl7jSD6mvWN05wokYFxUc9RT2p4kOkXPq26Wio4ksVJhFp1dkuJRyPIBW3xT2ipqnDmzUPzC4nKEwZC6vRz0sU4I7fFKLqGf4fmvi2nmJile-ctfcN8GV2Cam84WAgiIg7LrzYFQMeIj0fAmeBUXO4TAddsF6l6_JJu3uDXnzrDYJL9bEZiTk3Anf4SVeTle-hLDeAkTGbHI0Juqf1SEegGMRQ0mM0xcZe7Hmn3CFul3ahfEvGAYyny2tzHNUw'}

so i can do this:

jwt.decode(token, audience="secret-client-id", algorithms=['RS256'], key=key)

jade kite
#

Hello, why am I getting these errors in my Chrome console? Everything works fine but was just wondering what it could be. Thanks!

woeful mica
#

Hey, does someone know a python library for web push notifications? Creating the vapid keys (private & public) & sending the notification to a browser using the keys? Tag me if you know

rotund perch
#

Hello, how to configure config variables in heroku for django? (postgresql database variables)

odd belfry
rotund perch
odd belfry
#

yes

rotund perch
#

thanks !

odd belfry
fathom mist
odd belfry
fathom mist
#

Sorry I forgot to push my code

#
class PostCommentDeleteView():
    model = Comment
    fields = ['content']
    template_name = 'blog/post-detail.html'
    
    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False
        
    def get_success_url(self):
        return reverse_lazy('post-detail',kwargs={'pk':self.kwargs['pk']})    
odd belfry
fathom mist
#

Oh sorry

#

Yeah it works now

odd belfry
fathom mist
#

django.db.utils.IntegrityError: The row in table 'blog_comment' with primary key '15' has an invalid foreign key: blog_comment.author_id contains a value 'Ayman' that does not have a corresponding value in auth_user.id.

#

I'm also getting this error

#

@odd belfry

#

I get this error while I'm trying to migrate

#
class Comment(models.Model):
    post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
    author = models.ForeignKey(User,on_delete=models.CASCADE)
    content = models.TextField()
    date_added = models.DateField(auto_now_add=True)```
odd belfry
#

which column you are altering?

fathom mist
#

the author, it was set to this py author = models.CharField(max_length=32,default='Unknown')

odd belfry
#

you are changing char field to foreign key field, right?

fathom mist
#

yeah

odd belfry
#

there are several ways

#

before migrate, need to replace author name with author.id with update query

#

if author_id not found with current author name, then need to set a valid user id (cause your filed is non nullable)

fathom mist
#

But I don't have author name anywhere

odd belfry
#

yes

fathom mist
#

Cannot assign "'Ayman'": "Comment.author" must be a "User" instance.

#

I'm getting this error now

misty bough
#

hi everyone. I tried to build a flask simple website but it gave me a 404 so I tried on another website I created which was working and it gave me a 404 for all of my websites which are working!

#

please help me

misty bough
#

which one?

normal nova
#

Script that is giving 404

misty bough
#

this is a test I did that didn't work also

#

all of them are not working

#

anymore

#
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'
normal nova
#
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!' 

if __name__ == '__main__':
                app.run(debug=True)
#

Try this

gentle ingot
#

Can I automate a website updating based on a hit repo commits?

sacred crane
#

fastapi.exceptions.FastAPIError: Invalid args for response field! Hint: check that <class 'main.SoluteSolvent'> is a valid pydantic field type getting this error while executing the fastapi code

normal nova
misty bough
#

?

sacred crane
normal nova
misty bough
#

everything is ok there

normal nova
#

You are using pycharm?

misty bough
#

vsc

normal nova
#

I think you are not running the script properly.

#

Ctrl + s to save file

#

Run the file through terminal

#

python filename

#

And make sure url is using '/' route on browser

misty bough
#

didn't work

normal nova
#

Visit that url and share browser screenshot with url.

misty bough
normal nova
#

Add '/'

#

In url

misty bough
#

it removes the / when I press enter

normal nova
#

Route is fine. Code is fine.

#

Where is the debug status?

#

It prints 404 in terminal?

#

After visiting browser

misty bough
#

didn't add anything

granite solar
#

You can close and restart the server

misty bough
#

the number of times I did that is infinite

granite solar
#

okok

#

i have no more solutions:(

normal nova
#

Update flask to the latest version

#

Which version you are running?

misty bough
wild cedar
#

Why does it make it so when the window resizes it moves with it but when I scroll down in the page the background stops? And there is a white part there?

body {
    background-image: url(../img2/Picture1.png); 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    background-repeat: no-repeat;
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
   }```
obtuse plank
#

Hello

#

Is it possible to build an array in a for loop and use it in another loop?

#

Currently it's being duplicated

#

In PHP I would normally assign it to a key(based on the index) and display that

normal nova
misty bough
#

didn't work

#

this is so annoying

#

it worked yesterday

#

but not anymore

normal nova
#

Did you moved it's directory?

#

Create a new environment

misty bough
#

it works

#

I restarted my laptop

#

now it's working

cedar imp
#

if name == 'main':
app.run(debug=True, port=1234)

#

try that

misty bough
#

it's working

#

but it is openning a different website in a different repsoitry which is closed

fathom mist
#

Why am I getting this error

#
Views.py

class PostCommentCreateView(LoginRequiredMixin, CreateView):
    model = Comment
    fields = ['content']
    template_name = 'blog/comment_form.html'

    def form_valid(self, form):
        form.instance.post_id = self.kwargs['pk']
        form.instance.author = self.request.user
        return super().form_valid(form)

    def get_success_url(self):
        return reverse_lazy('post-detail',kwargs={'pk':self.kwargs['pk']})

class PostCommentUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Comment
    fields = ['content']
    template_name = 'blog/comment_form.html'

    def form_valid(self, form):
        form.instance.post_id = self.kwargs['pk']
        form.instance.author = self.request.user
        return super().form_valid(form)

    def get_success_url(self):
        return reverse_lazy('post-detail',kwargs={'pk':self.kwargs['pk']})
    
    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False
    
class PostCommentDeleteView(DeleteView):
    model = Comment
    fields = ['content']
    template_name = 'blog/comment_confirm_delete.html'
    
    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False
        
    def get_success_url(self):
        return reverse_lazy('post-detail',kwargs={'pk':self.kwargs['pk']})   
#
Urls.py

    
    path('post/<int:pk>/comment/', PostCommentCreateView.as_view(), name='post-comment'),
    path('post/<int:pk>/comment-update/', PostCommentUpdateView.as_view(), name='post-comment-update'),
    path('post/<int:pk>/comment-delete/', PostCommentDeleteView.as_view(), name='post-comment-delete'),
#
Models.py

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.TextField()
    date_added = models.DateField(auto_now_add=True)

    def __str__(self):
        return '%s - %s' % (self.post.title, self.author)
lilac solar
#

You don't have a Comment with a pk of 4 in your database

#

It matches the expected URL but the query to fetch the comment is returning nothing

thin lance
#

post or get

fathom mist
thin lance
fathom mist
#

Oh sorry

fathom mist
indigo kettle
#

UpdateView by default looks for the path parameter called pk. Since you are telling it that the model for PostCommentUpdateView is Comment it is looking for a Comment with pk=4

#
path('post/<int:post_pk>/comment-update/<int:pk>/', PostCommentUpdateView.as_view(), name='post-comment-update'),
#
class PostCommentUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Comment
    fields = ['content']
    template_name = 'blog/comment_form.html'

    def form_valid(self, form):
        form.instance.post_id = self.kwargs['pk']
        form.instance.author = self.request.user
        return super().form_valid(form)

    def get_object(self, *args, **kwargs):
        return get_object_or_404(self.model, pk=self.kwargs['pk'], post=self.kwargs['post_pk'])

    def get_success_url(self):
        return reverse_lazy('post-detail',kwargs={'pk':self.kwargs['pk']})

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False
fathom mist
#

Wait it's not working again

austere relic
#

@upbeat ruin you can write to a file maybe?

native tide
#

Hi, Im making web scraper and i have problem with UL and LI, when i try to scrape them i get only this ```
</ul>
<ul class="connectedState" id="state1">
</ul>

 but in google its filled with <li>? anyone know why?
mystic cobalt
#

I was wondering how I could create a html button that executes a python flask file in my directory, or if that's even possible.

visual cedar
#

I'm looking to switch between databases depending on how I run Django. For example, it's a huge pain to get mssql server up and running for github actions ci/cd, so I want to use sqlite3 for that portion, but I want to stick with mssql server when I run python manage.py runserver. How do I create this split?

frank shoal
#

Using sqlalchemy?

#

You can conditionally set an environment variable containing a database url

#

I.e. dialect://user:pass@host:port/db

lavish prismBOT
frank shoal
#

<@&831776746206265384> here too

visual cedar
visual cedar
# frank shoal <@&831776746206265384> here too

Oh one question though, it looks as though I should be able to specify which database to run? because the way settings.py DATABASES is written

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'mydatabase',
    }
}

Can't I just add the ability to set the DB by adding an argument like python manage.py test --use-db default? somehow? this is probably way more complex but might use less dependencies.. or maybe I have no idea what I am saying

frank shoal
#

Don't see why not

visual cedar
#

Ah my question was a little half baked, what I meant to actually ask is

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'mydatabase',
    }
    'db2': { ...
    }
}

How would I tell django to seek out db2 when running python manage.py test or manage.py runserver?

frank shoal
#

Set a value when runserver is used

visual cedar
#

Do you mean like

if sys.argv[1] == 'runserver':
  DATABASES = { 'db2': {...} }
#

ah I dont think I can do that since it will tell me that default is required or something

indigo kettle
#

doesn't test create an entirely different database to test on?

#

I'm not sure this is necessary

#

it is common to use many settings files, one for each environment you might need like settings_local.py, settings_dev.py, settings_prod.py. You can define different DATABASES in each. Maybe that's what you want?

visual cedar
visual cedar
#

Upon doing a little bit of debugging, print(Snippet.objects.all()) within my test returns a queryset with pks not starting at 1

#

Thanks I'll give that a read and see if it gives me hints

indigo kettle
#

do you have many tests which set up and create snippets?

#

you have a set_up method in your test class I believe that gets run once per test

#

so you could be creating and deleting many snippets

visual cedar
#

I have two tests, and yeah indeed I have a setup that only initializes an object and creates two snippets

#

but in my first test case I am not creating further snippets, only this:

        snippet1 = Snippet.objects.get(pk=1)
        snippet2 = Snippet.objects.get(pk=2)
indigo kettle
#

it may be illuminating to print something out during your setup

#

to see if it is running multiple times

visual cedar
#

Good idea, I'll try that

#

You're a genius, that was the easiest debugging trick ever

#

I found out that this whole test thing is being called twice, which generates two sets of snippets

visual cedar
indigo kettle
#

yeah, I had a feeling!

visual cedar
#

is the solution to have a init(self): constructor that establishes my objects?

indigo kettle
#

is it important these primary keys be 1 and 2?

#

it seems weird to test on that

#

using set_up should be good

visual cedar
#

Not exactly, I'm new to testing though so I have no idea what I'm supposed to test 😉

#

My first instinct was to test to make sure models actually get made and they can be accessed

#

Second instinct was to test that saving them to the db is possible at all

indigo kettle
#

It seems like you are trying to test things which django already tests for thoroughly

#

you need to test the things you have written

#

not django's code

visual cedar
#

fair enough, I suppose yeah django does check that I wrote my models and serializers correctly

indigo kettle
#

if you had a custom save method which updates a modified_at field or something, you could create a model and check that the modified_at field changes after re-saving

#

if you really want to check that objects are being saved you can check the Snippet.objects.count() before. Then save x new snippets and check that the new count is x more than it was originally

visual cedar
#

Ah yes that was my intention, but I wrote spaghetti instead

indigo kettle
#

it's hard to know what to do when you're just starting

#

I still don't know

#

so

visual cedar
#

but from what you said, I suppose I should just trust that methods do what I expect them to do if I didnt write them

#

so maybe checking objects being created and saved is redundant

indigo kettle
#

yeah that's a fairly common idea in testing

#

I would say it is

visual cedar
#

Ok great, thanks a lot. I learned so much just now

indigo kettle
#

🙂

fathom mist
indigo kettle
#

you changed the url like i posted before?

#

you could just use self.kwargs['post_pk']

visual cedar
#

Another Django question, but when I run python manage.py runserver, I think the code inside of it gets executed twice. Is this normal? For example if I put a print statement print("print statement inside settings.py") in there, I get this in my console

$ python manage.py runserver
print statement inside settings.py
print statement inside settings.py
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
#

Aha, found the solution. For those wondering, Django does indeed read settings.py twice! This is because Django wraps settings.py and does things at a lower level with it, so print statements will appear twice.

#

It is not a bug though apparently!

#

More reading revealed to me that

Django uses two process for the reloading feature (ie. restart on code change), if you run ./manage.py runserver --noreload you get only one process.

Sorry for answering my own question. I figure this will help those who try to use search in discord

fathom mist
fathom mist
sacred crane
#

when i feed this as input in fastapi CC(C)(C)Br in get request url the ( is converting into % some number how to stop this

#

inputs

dusk portal
#

hey

#

can i use redis without django channels?

candid panther
#

Hey I need to customise the login function in django, what should I do to get it done. I have used a custom authentication backend for this and I'm getting the user from it but when I pass that user to the login() it won't create session for the user. What should I do now?

noble spoke
dawn island
#

I have been trying social media authentication in django, so I used python soical auth and was successfully able to log users in, I am trying to get profile photo of the logged in user, and save it in my backend. I don't know how to do it ,can some one pls share.

austere relic
#

have them upload images, then store them somewhere?

austere relic
fathom mist
#

When I try to update a comment I get this

#
Views.py
class PostCommentUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Comment
    fields = ['content']
    template_name = 'blog/comment_form.html'

    def form_valid(self, form):
        form.instance.post_id = self.kwargs['pk']
        form.instance.author = self.request.user
        return super().form_valid(form)

    def get_success_url(self):
        return reverse_lazy('post-detail',kwargs={'pk':self.kwargs['post_pk']})
    
    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False
    
class PostCommentDeleteView(DeleteView):
    model = Comment
    fields = ['content']
    template_name = 'blog/comment_confirm_delete.html'
    
    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False
        
    def get_success_url(self):
        return reverse_lazy('post-detail',kwargs={'pk':self.kwargs['post_pk']})  

#
Models.py
class Comment(models.Model):
    post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.TextField()
    date_added = models.DateField(auto_now_add=True)

    def __str__(self):
        return '%s - %s' % (self.post.title, self.author)
#
Urls.py

    path('post/<int:post_pk>/comment/', PostCommentCreateView.as_view(), name='post-comment'),
    path('post/<int:post_pk>/comment-update/<int:pk>/', PostCommentUpdateView.as_view(), name='post-comment-update'),
    path('post/<int:post_pk>/comment-delete/<int:pk>/', PostCommentDeleteView.as_view(), name='post-comment-delete'),```
#
Post_detail.html
<div>
     <a class="btn btn-secondary btn-xs mt-1 mb-1" href="{% url 'post-comment-update' post.id comment.id %}">Update</a>
     <a class="btn btn-danger btn-xs mt-1 mb-1" href="{% url 'post-comment-delete' post.id comment.id %}">Delete</a>
</div>
karmic star
#

How to serialize a response containing nested list, inner list are list of objects.
something like this, [[obj 1, obj 2, obj 3], [obj 4, obj 5, obj 6]]

I'm able to serialize, [obj 1, obj 2, obj 3] by passing many=True in schema object for the model, but in the previous response the same schema is returning empty responses.

#

see the logs, it's printing correctly but when returning the list getting empty response in the list

heavy dagger
#

why doesnt this button work?

tiny snow
heavy dagger
karmic spoke
heavy dagger
#

alright i got it

#

thanks

karmic spoke
#

or just make a .js file

tiny snow
#

Usually, scripts are put at the end of the body tag

heavy dagger
#

yeah and?

karmic spoke
#

and add the <script tag on the end of body tag

tiny snow
#

But, yeah, a file is good too

heavy dagger
#

script sclrc

#

src*

#

okay

karmic spoke
#

with src='yourfile.js'

tiny snow
#

yeah

<script src="yourfile.js"></script>
heavy dagger
#

ayt tysm

#

:)

karmic spoke
#

anyone can help me with this?

#

It's something with the sessions and session tokens idk

lilac solar
#

!rule 5?

lavish prismBOT
#

The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.

karmic spoke
#

breach tos?

#

It's just webscraping?

lilac solar
#

Yep. I couldn't see an explicit API section and most companies won't allow scraping by default

karmic spoke
#

Wtf why

#

It's just bundling info which is available for everyone

heavy dagger
karmic spoke
heavy dagger
#

to the button aswell?

barren solar
#

change your function name to something else, for example "onClick"

tiny snow
#

What if you put the script tag between the paragraph element and the button element?

heavy dagger
#

No heres the problem what i found

#

the script inside onclick should be put in double quotes

#

like onclick = "script"

#

and i used java script double quotes aswell

#

so like if i used single quotes there wouldnt be a problem

golden bone
#

Please see the rules, looking for paid work is not allowed on this server

dawn heath
native tide
#

Hello folks,
I'm trying to register a blue print in flask that will handle custom exceptions,

when I do app.register_blueprint(config_error_handler_bp), the exceptions isn't caught
why is that ?
but if the blueprint that's raising the exception is the one that's decorated with the error_handler decorator, it does catch it

late dock
#

im making a web application in angular that will need a REST API and websockets (for messages) and authentication, and have trouble deciding my back end framework, it's between flask and django

I've used neither (only spring / spring boot, asp.net / .net), i do have experience in python tho

I've done some research on the frameworks and know that flask is more barebones and django includes a lot more functionality, but I'm not quite sure if django would be overkill for my needs or not

inland oak
#

there is project to resolve your websockets: Django Channels

#

there is project to have everything out of the box for REST API: Django Rest Framework

#

Flask should be having its own analogs though, but I never tried them, just heard about Flask Restful

serene prawn
#

FastAPI could be a better choice than flask

broken oar
#

I was just deciding on learning a back-end framework

native tide
serene prawn
# native tide why ?

It offers the same set of features but is more performant, has built-in DI system and is integrated with pydantic providing data validation and openapi spec

native tide
#

Nice

#

And what are the options when it comes to deployment ?

serene prawn
#

wdym?

native tide
#

Where can you deploy it ?

serene prawn
#

It's not different from deploying any other python web app

native tide
#

I know, i'm talking about support

#

because for example

#

I've just read that pythonanywhere doesn't support asgi

#

Because I have 2 apps deployed on pythonanywhere

#

and i thought about switching to FastAPI for better performane

#

but i think it'll be better to move from pythonanywhere, because it's very limite

#

d

serene prawn
#

Why not use any vds provider instead?

native tide
#

Idk what that is

tepid lark
#

FastAPI is great... if you're building an API.

mental summit
serene prawn
tepid lark
#

I like using SPAs... hate having to build them.

#

Also, it's easy to package FastAPI in a Docker container with uvicorn and a reverse proxy of your choice.

serene prawn
#

It's really more about developer experience

tepid lark
#

Yeah, just run docker on a cheap vps with *docker compose and you're set.

#

Ooh, DO has a container registry product now.

#

Anyways, I wanted to brainstorm some architecture.

#

I have an API backend (Django because we known Django) and SPA frontend. Both the frontend and backend are behind a CloudFront distribution. The backend is ECS and we pass traffic with a certain path back to it. Frontend is served from S3 with CloudFront acting as a CDN.

#

I'm thinking I could replicate this locally with Nginx as a reverse proxy serving the SPA statically and passing traffic through to the backend container.

late dock
#

cool, thanks :)

agile folio
#

is this web-dev including questions regarding Web3 and Dapp?

dawn heath
native tide
#

Has anyone setup the python backend in cpanel for a website?

mystic cobalt
#

I was wondering how I could create an html button that executes a python flask file

inland oak
inland oak
#

Div object can be made looking as custom looking button. Wrapping to a tag will make it calling GET request to specified url

#

And finally attaching JavaScript event listening to click, can make any object to call any type of request

sacred crane
#

How to connect celery with flask and Redis as message broker and do machine learning predictions

#
# flask rest API code for inference
response = {}
@app.route('/predict', methods=["POST", "GET"])
def predict():
    if request.method=='POST':
        solute = request.form["solute"]
        solvent = request.form["solvent"]

    else:
        solute = request.args.get("solute")
        solvent = request.args.get("solvent")

    results = predictions(solute, solvent)
    
    response["predictions"] = results[0].item()
    response["interaction_map"] = (results[1].detach().numpy()).tolist()
    return flask.jsonify({'result': response})
#

I am doing inference of a machine learning PyTorch model and want to use celery and Redis for queuing prediction. I have written the inference code in the flask as a rest API and now got confused about how to add celery tasks and Redis message broker.

frank shoal
#

are you on windows?

sacred crane
#

@frank shoal yes

#

I am using flask

frank shoal
#

it still applies

cerulean badge
#

(context django) how can I create a custom model field for chess.Board class of python-chess lib? I read the docs but they are too hard for me to follow. I think subclassing CharField and saving FEN strings provided by board.fen() would do the job.

raven night
#

Good morning I want to ask if somebody can help me. I want to but music over a whole website so that if you open a new html file the music is still playing. over every file in the website

meager anchor
#

looking at the python-chess docs, i'd probably do the same

sullen spindle
#

Hello Guys, we have used python flask for developing the website https://avilpool.xyz/. Frontend is html coded. Need your comments on this.

tender willow
#

hello

#

i have a bug in my program i just joined how to fix it

#

anyone can help ?

sullen spindle
warped aurora
#

ive got a form that looks like that, each row represent a record in the database and I want to submit this through ajax, what would be the best way to pass the data? Should I put each row in it's on form and then try to submit multiple forms at once through ajax? or maybe build a list of some sort and submit the list as a single form?

rigid laurel
warped aurora
sacred crane
#

I am trying to queue predictions using celery in flask . I was trying to add async results in celery but i have no idea where to add can some one please help - https://docs.celeryproject.org/en/stable/reference/celery.result.html

def predictions(solute, solvent):
    mol = Chem.MolFromSmiles(solute)
    mol = Chem.AddHs(mol)
    solute = Chem.MolToSmiles(mol)
    solute_graph = get_graph_from_smile(solute)

    mol = Chem.MolFromSmiles(solvent)
    mol = Chem.AddHs(mol)
    solvent = Chem.MolToSmiles(mol)
    solvent_graph = get_graph_from_smile(solvent)


    delta_g, interaction_map =  model([solute_graph.to(device), solvent_graph.to(device)])
    return delta_g, torch.trunc(interaction_map)

@celery.task()
response = {}
@app.route('/predict', methods=["POST", "GET"])
def predict():
    if request.method=='POST':
        solute = request.form["solute"]
        solvent = request.form["solvent"]

    else:
        solute = request.args.get("solute")
        solvent = request.args.get("solvent")

    results = predictions(solute, solvent)
    
    response["predictions"] = results[0].item()
    response["interaction_map"] = (results[1].detach().numpy()).tolist()
    return flask.jsonify({'result': response})
wet idol
#

hi can anyone please help me with disabling back button once user logs out from an app in flask (without deleting cache)

frank shoal
#

that would be done with javascript.

frank shoal
wet idol
late stone
#

hello friends

#

is anyone familiar with django messaging framework?

#

how would you make a django message to go away after x amount of secs?

dawn heath
#

I need to create the following flow in django ,. how is this possible?

#
1. User sends a request to the web server. A direct access to the database is forbidden.

2. The request is sent to the authentication server to be validated.

3. Authentication server provides an access token that can be expired after a short period.

4. Web-server verifies an access token and responds with decrypted data.
strong stirrup
#

<link rel="stylesheet" href="{{ url_for('static',filename='style.css') }}" />

#

this is getting a lot of errors

#

why

drifting radish
#

File "manage.py", line 42, in <module> main() File "manage.py", line 38, in main execute_from_command_line(sys.argv)

cedar imp
#

Does anyone has a nice Flask community server maybe?

mental summit
#

You’ll have to scroll up a little actually

torn silo
#

hello guys, i use Vue and Django and my cookies are not setting, when i make request in insomnia my cookies are set

upper turret
#

hello,I am new to Django and I wanted to know why do we have to use modelform as we can get the data through a form created by html.Thanks!

golden bone
torn silo
#

When i have app A in django and i login, can i use sessionid in app B? In my project dont work it, but i hope that its problem

native tide
#

How would you go about storing data for a survey?

#

There's about 20 questions that use radio dials and want to loop through them and get question, and both extreme points

thorn igloo
#

what's the issue?

#

that's the ip you're visiting?

#

yeah i think you need to use something like ngix

#

an article from digital ocean. id say follow this

thorn igloo
#

what do you want to do here? run this in production or development?

thorn igloo
#

i dont understand why you would want to run this in development on digitalocean

#

currently the way it is, this thing is only available on localhost, on wherever your droplet is being hosted

#

it's not being exposed to the public

#

much similar to how a local server works on your pc

devout aurora
#

@thorn igloo ^

thorn igloo
#

dont you still have the droplet?

#

but anyways, my point still stands, no point in running this in development on digitalocean

#

just use gunicorn or so

devout aurora
thorn igloo
thorn igloo
# devout aurora i don’t know how… can u add me, i wouldn’t mind paying u a lil to help me set it...
DigitalOcean

In this guide, you will build a Python application using the Flask microframework on Ubuntu 20.04. The majority of this tutorial is about how to set up the Gunicorn application server to run the application and how to configure Nginx to act as a front

#

actually this is better

#

might even have what you're looking for

undone forge
#

And boom it works

#

Even without using socket

ocean slate
#

hello

#

help

hollow verge
#

I have flask app and I have created virtual env. in this but when I try to install packages with req.txt file I get this error

ocean slate
#

how I can make a popup box when I go to specific box

hollow verge
#
ERROR: Failed building wheel for scipy
  Running setup.py clean for scipy
  ERROR: Command errored out with exit status 1:
   command: /home/ubuntu/huawei-knowledge-graphs/PD/myprojectenv/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-th7_4ljx/scipy/setu
p.py'"'"'; __file__='"'"'/tmp/pip-install-th7_4ljx/scipy/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"'
);f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' clean --all
       cwd: /tmp/pip-install-th7_4ljx/scipy
  Complete output (11 lines):
  /tmp/pip-install-th7_4ljx/scipy/setup.py:116: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
    import imp
  
  `setup.py clean` is not supported, use one of the following instead:
  
    - `git clean -xdf` (cleans all files)
    - `git clean -Xdf` (cleans all versioned files, doesn't touch
                        files that aren't checked into the git repo)
  
  Add `--force` to your command to use it anyway if you must (unsupported).
  
  ----------------------------------------
  ERROR: Failed cleaning build dir for scipy
Failed to build psycopg2 psycopg2-binary scipy
ERROR: pandas 1.3.5 has requirement python-dateutil>=2.7.3, but you'll have python-dateutil 2.7.2 which is incompatible.
ERROR: scikit-learn 1.0.2 has requirement scipy>=1.1.0, but you'll have scipy 1.0.1 which is incompatible.
Installing collected packages: attrs, click, Werkzeug, itsdangerous, MarkupSafe, Jinja2, Flask, Flask-Login, greenlet, SQLAlchemy, Flask-SQLAlchemy, numpy, pytz, six, python
-dateutil, pandas, passlib, pluggy, psycopg2, psycopg2-binary, py, pytest, threadpoolctl, scipy, joblib, scikit-learn, sklearn, jellyfish, recordlinkage
    Running setup.py install for psycopg2 ... error
#

I want to deploy my site

#

I have installed this packages in my local machine it didn't gave me this error but when I use venv I get this error

ocean slate
#

IDE name?

hollow verge
#

no IDE

#

using terminal

ocean slate
#

pip install flask

#

used this cmd?

hollow verge
#

yes

#

i have install wheel also

#

using pip install wheel

ocean slate
#

using python 3?

#

python3 -m pip install --upgrade pip

#

upgrade pip by this

hollow verge
#

already upgreaded

ocean slate
#

pip install scipy-0.16.1-cp27-none-win_amd64.whl

#

use this now

#

after updating

hollow verge
#

WARNING: Requirement 'scipy-0.16.1-cp27-none-win_amd64.whl' looks like a filename, but the file does not exist
ERROR: scipy-0.16.1-cp27-none-win_amd64.whl is not a supported wheel on this platform.

#

got this

ocean slate
#

pip install C:\Python27\numpy-1.11.2rc1+mkl-cp27-cp27m-win32.whl
pip install C:\Python27\scipy-0.18.1-cp27-cp27m-win32.whl

hollow verge
#

I am using linux

ocean slate
#

oo

#

ubuntu?

hollow verge
#

yes

ocean slate
#

$ sudo apt-get install libatlas-base-dev gfortran
$ sudo pip3 install scipy

#

try this

hollow verge
#

wait

#

now which command?

ocean slate
#

$ sudo apt-get install libatlas-base-dev gfortran

#

$ sudo pip3 install scipy

#

one by one

hollow verge
#

installed t

#

next?

ocean slate
#

what is showing

hollow verge
#

installed

#

but I have to installed every package form req.tx

ocean slate
#

pip install -r requirements. txt

hollow verge
#

yes I dont that

#

done*

ocean slate
#

what is the problem then?

hollow verge
#

got this

ocean slate
#

have u installed libpq-dev

#

?

hollow verge
#

yes

ocean slate
#

sudo apt-get install libpq-dev

#

by this cmd?

hollow verge
#

see I want to deploy this site with gunicorn but for that I need virtual env right?

#

can I do that without that?

ocean slate
#

i think no

#

probably

#

because I havnt done before

hollow verge
#

because every config I see it has virtual env

#

You have deployed any flask app on virtual machine?

ocean slate
#

so i can not guide anything related this deployment

hollow verge
#

ok

glacial portal
#

How do I make a subdomain?

inland oak
lyric parrot
#

hi im trying to run my web in vscode but it wouldn't run it says (Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.) so anyone could help me to run it ?

glacial portal
#

Oh wait

How do I connect my website as a subdomain using flask? (In one hosting)

lyric parrot
#

or tell me what should i do

#

?

inland oak
glacial portal
#

How do I do that then? thinkmon

glacial portal
#

Code wise thinkmon

inland oak
#

U setup DNS settings for your domain

Using GUI in Domain provider
Or terraform / pulumi any other infra tool to do the same as code

glacial portal
#

Oh it's not easy then pithink

inland oak
#

Pulumi has Python support ;)

inland oak
# glacial portal <@370435997974134785>

I explained how to set subdomain for real server.

The guide explained two things

  1. how to test domain restricted applications at developer machine (useful)

  2. how to have routing at flask application level to handle two domains from same application.(in my opinion that is useless information, because usually we want second domain for second application. I never encountered the need to handle two domains from one application. That is silly and against microservices approach)

#

Monolith is not the way.

lyric parrot
#

im sure that its not form the pc its form vscode cause i wrote in the cmd and it was all right

inland oak
inland oak
#

And in corner of vscode, select venv path to it, if it was not autselected

#

In 99.999% cases we don't need vscode access to global python anyway

lyric parrot
#

it tells me the same when i try to make a venv

inland oak
# glacial portal <@370435997974134785>

The whole purpose of subdomains is to have different application from different IP to it.

If it is the same app. Just use different sub path.

The only case when it is acceptable to direct two domains to one ip... In k8s ingress. And in nginx reverse proxy. Because they both fastly making internal redirects to different apps

lyric parrot
#

i wrote (python -m venv work_env) in the terminal

inland oak
#

Bottom left of right

serene prawn
serene prawn
#

I thought it was exactly nginx + k8s

#

😅

inland oak
#

I would have added k8s prefix then ;b

glacial portal
inland oak
#

I didn't ever use ingress outside of k8s, I wonder if it is possible or it is purely kubernetes native app

inland oak
inland oak
# glacial portal I see thanks! But I don't know much about nginx or the other one I'll learn it l...
serene prawn
inland oak
serene prawn
#

If you use nginx solely as a reverse-proxy then not really

inland oak
#

Ingress is for routing
Traffic reverse proxy + advanced caching

#

Nginx can do caching too though

serene prawn
#

Traefik can do simple load balancing, and caching is only available in enterprise version 🤔

inland oak
#

Haproxy could work as a free load balancer

#

Or just to use cloud providers lbs

sacred crane
#

I am doing prediction on a machine learning model using PyTorch and in Django rest framework. while loading I am getting TypeError: 'method' object is not subscriptable error. How to rectify this error. My views.py file

response = {}
@api_view(['GET'])
def result(request):
    solute = request.POST.get['solute']
    solvent = request.POST.get['solvent']
    results = predictions(solute, solvent)
    response["predictions"] = results[0].item()
    response["interaction_map"] = (results[1].detach().numpy()).tolist()
    return Response({'result': response}, status=200)                                                 
#
class ApiConfig(AppConfig):
    name = 'api'
    MODEL_FILE = os.path.join(settings.MODELS)
    model = joblib.load(MODEL_FILE)  
``` my `apps.py` file
serene prawn
#

You're using dict.get wrong

inland oak
sacred crane
serene prawn
#

Either do request.POST["key"] or request.POST.get("key")

sacred crane
#

do i need to use {}

serene prawn
#

request.POST is a simple dictionary object

#

the same as {} or dict()

sacred crane
#
  File "C:\Users\MAHESH\Desktop\iiit hyderabad\django rest api\api\views.py", line 384, in result
    solute = request.POST['solute']
  File "C:\Users\MAHESH\anaconda3\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__
    raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'solute' 
```  after changing i got this error
inland oak
#

There is no value with this key I guess

#

Use get to be not having errors if there is no strict need to have it, optionally provide default value
Or try catch error and do what needs to be done in case it is missing

inland oak
serene prawn
#

Yep, you should be using forms

inland oak
#

I remember they were in dictionary ending with .data

sacred crane
sacred crane
serene prawn
#

Then use drf

#

Or other framework like FastAPI, i personally don't really to write api's using django

inland oak
#

request.POST.data ?

serene prawn
inland oak
#

Or request.data I don't remember

sacred crane
#
@app.route('/predict', methods=["POST", "GET"])
def predict():
    if request.method=='POST':
        solute = request.form["solute"]
        solvent = request.form["solvent"]

    else:
        solute = request.args.get("solute")
        solvent = request.args.get("solvent")

    results = predictions(solute, solvent)
    
    response["predictions"] = results[0].item()
    response["interaction_map"] = (results[1].detach().numpy()).tolist()
    return flask.jsonify({'result': response})
``` flask code
inland oak
#

Huh. Celery is agnostic to framework

serene prawn
#

If you're using drf at this moment then you should use serializers to validate and clean your data

sacred crane
inland oak
#

They have valid enough getting started instructions

#

There are no attachments to specific framework

#

In its original version at least

sacred crane
#

ok

inland oak
serene prawn
#

Yep

#

Serializers != Models

#

You would still use pydantic models(serializers) in fastapi app, right?

#

Even if there's no db interactions

inland oak
#

I guess it makes sense. Getting nice inbuilt JSON errors from validators work

inland oak
serene prawn
#

Just as an example:

class UserCreateSerializer(serializers.Serializer):
    username = serializers.CharField(min_length=3)

It's guaranteed to be a string, otherwise when doing any operation on something that you expect to be a string you'd just 500:

username = None
username.lower()
inland oak
#

For now all the different DevOps tools consume my time ;)
Going to setup monitoring/logging/autoalerts in k8s next

inland oak
#

I wonder if DRF can catch it

#

Or without db in drf it would not give error

serene prawn
#

Catch what? 🤔

inland oak
serene prawn
#

It would, you should just create your serializer and validate it

#
from rest_framework import serializers

class CommentSerializer(serializers.Serializer):
    email = serializers.EmailField()
    content = serializers.CharField(max_length=200)
    created = serializers.DateTimeField()

serializer = CommentSerializer(data={"some": "data"})
serializer.is_valid(raise_exception=True)
inland oak
#

Let's assume that while not tested it is not guaranteed in drf ;)

serene prawn
#

Wdym it's not guaranteed?

inland oak
#

Thanks

#

I can see now

serene prawn
inland oak
#

That is why was doubtful

serene prawn
#

Yep, there's ModelSerializer but if you expect some data to be in your query for example you could create a serializer for it

inland oak
#

I see no problems here.
Query URL data can be accessed in same dictionary way as post data

serene prawn
#

I know that drf has built-in pagination, but it's just an example:

class Query(serializers.Serializer):
    page = serializers.IntegerField(min_value=1, default=1)
    page_size = serializers.IntegerField(min_value=1, max_value=1000, default=100)
def some_view(request):
    query_serializer = Query(request.params)
    query_serializer.is_valid(raise_exception=True)
    query_data = query_serializer.validated_data
#

Not all of your data would come from db, you might call other services, so using something like django-filter is really meaningless here

sacred crane
#
class Prediction(serializers.Serializer):
    solute = serializers.CharField()
    solvent = serializers.CharField()
``` I have created serializer now i want to use this serializer inside views how can i use it?
#
response = {}
@api_view(['GET'])
def result(request):
    solute = request.POST.get('solute')
    solvent = request.POST.get('solvent')
    results = predictions(solute, solvent)
    response["predictions"] = results[0].item()
    response["interaction_map"] = (results[1].detach().numpy()).tolist()
    return Response({'result': response}, status=200)
``` where should i have to keep here the above serialize in my `views.py` @serene prawn
serene prawn
sacred crane
#

but i am already using @api_view(['GET]) ??

serene prawn
#

Yep, you just need to use your serializer then, usually they're stored in separate module (e.g. serializers.py),

@api_view(['GET'])
def result(request):
    serializer_in = serializers.Prediction(data=request.data)
    serializer_in.is_valid(raise_exception=True)
    data = serialzier_in.validated_data
    
    response = {}
    results = predictions(data["solute"], data["solvent"])
    response["predictions"] = results[0].item()
    response["interaction_map"] = (results[1].detach().numpy()).tolist()
    return Response({'result': response}, status=200)
#

I just always used class-based views 😅

glacial portal
#

<div class="owo">
<div class="uwu">

is owo the parent and uwu is child?

#

Or this isn't a relationship?

inland oak
fickle mantle
#

I am struggling with my Flask SQAlchemy query. I have categorized articles. I can query the articles easily enough and get their associated categories. My problem is doing the reverse -- query the category and retrieve associated articles.

The following is from my models

`class Category(db.Model):

__tablename__ = "category"

id = db.Column(db.Integer, primary_key=True)
slug = db.Column(db.String(64), index=True, unique=True, nullable=False)
name = db.Column(db.String(128), nullable=False, index=True)

categories = db.relationship(
"Category",
secondary=article_categories,
lazy="subquery",
cascade="all,delete",
backref=db.backref("articles", lazy=True),

class Articles(db.Model):

`
and from my view

@artitcle.route("/category/<category_slug>", methods=["GET"]) def by_category(category_slug): category = Category.query.filter_by(slug=category_slug).first_or_404()

I can retrieve the category but I cannot retrieve the associated articles. Is there something missing from my model?

serene prawn
fickle mantle
# serene prawn Could you send code of both of your models again?

`class Category(db.Model):

__tablename__ = "category"

id = db.Column(db.Integer, primary_key=True)
slug = db.Column(db.String(64), index=True, unique=True, nullable=False)
name = db.Column(db.String(128), nullable=False, index=True)

article_categories = db.Table(
"article_categories",
db.Column("article_id", db.Integer, ForeignKey("articles.id")),
db.Column("category_id", db.Integer, ForeignKey("category.id")),
)
class Articles(db.Model):
categories = db.relationship(
"Category",
secondary=article_categories,
lazy="subquery",
cascade="all,delete",
backref=db.backref("articles", lazy=True),

__tablename__ = "articles"

id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, ForeignKey("users.id"), nullable=False)
uuid = db.Column(db.String(36), index=True, unique=True, nullable=False)
title = db.Column(db.String(180), index=True, unique=False, nullable=False)
released_at = db.Column(db.DateTime, nullable=True, index=True)

categories = db.relationship(
    "Category",
    secondary=article_categories,
    lazy="subquery",
    cascade="all,delete",
    backref=db.backref("articles", lazy=True),
)`
serene prawn
#

Use a codeblock

fickle mantle
serene prawn
#

@fickle mantle Why your categories relationship is in Category class though?

fickle mantle
south arch
#

Does someone know why Django Python gives me this error when trying to run python manage.py makemigrations?

if self.max_length is not None and choice_max_length > self.max_length:
TypeError: '>' not supported between instances of 'int' and 'str'

I have checked my models, everything looks fine.

twilit depot
#

anyone know anything about webscraping?

#

not sure if this is the right channel

#

kinda loopy rn

inland oak
twilit depot
inland oak
#

have a shame. it is supposed to be bought. google it on your own.

robust folio
#

heyy

#

can data of live website be changed?

empty parrot
#

Hey guys

inland oak
robust folio
inland oak
#

in many different ways

#

it depends on what you are wishing to achieve

robust folio
#

can unathorized user change data?

inland oak
#

if you will leave loopholes in your web server, then yes 😉

#

or if you will make interface to do so

twilit depot
#

ignore my autism

robust folio
#

ohh

native tide
#

I need to populate a survey with 3 different words for each input. Trying to figure out how to store the data to loop through it to auto-generate it

golden bone
left parrot
#

In this picture there is a yellow circle

#

inside the i

#

how can I place things like that over the text with html and css

warm igloo
#

With positioning. Look up absolute and relative positioning in CSS.

magic palm
#

Can anyone help with exchange codes?

native tide
#

If anyone knows how I would go about setting up an smtp server in python pls dm me

frank shoal
#

You don't set it, you pass it to the smtp module via functions

split snow
#

can someone help me with this? it is related with flask framework

Connection is my class btw

if I did this one

data = Connection(document = doc)
session.add(data)
session.commit()

it will raise error (psycopg2.errors.InFailedSqlTransaction) current transaction is aborted, commands
ignored until end of transaction block

and when I do this

data = Connection(document = doc)
session.add(data)
try:
    session.commit()
except:
    session.rollback()
    session.flush()

It does not save to db but it raise saved successfully please help

sacred crane
#

I am using Django rest framework to do prediction on two strings and using celery to run inference. But I was unable to make use of celery workers even though I have done everything perfectly. I am getting predictions from drf only

#

I am using redis as a broker.

#

My tasks.py

#
@shared_task(bind=True)
def predictions(self,solute, solvent):

    mol = Chem.MolFromSmiles(solute)
    mol = Chem.AddHs(mol)
    solute = Chem.MolToSmiles(mol)
    solute_graph = get_graph_from_smile(solute)

    mol = Chem.MolFromSmiles(solvent)
    mol = Chem.AddHs(mol)
    solvent = Chem.MolToSmiles(mol)
    solvent_graph = get_graph_from_smile(solvent)
    delta_g, interaction_map = model([solute_graph.to(device), solvent_graph.to(device)])
    return delta_g, torch.trunc(interaction_map)
#
#My `views.py`  
@api_view(['GET'])
def result(request):
    response = {}
    solute = request.GET.get('solute')
    solvent = request.GET.get('solvent')
    results = predictions(solute,solvent)
    response["interaction_map"] = (results[1].detach().numpy()).tolist()

    response["predictions"] = results[0].item()

    return Response({'result': response}, status=200)
#

I guess the problem is not adding .delay() to results = predictions(solute,solvent) but if I add results = predictions(solute,solvent).delay() I am getting error.

#

Even though I am getting my prediction perfectly without any error their is no celery task is running please help me where I am doing wrong

#

flower panel

serene prawn
crude stirrup
#

what's the difference between EmailField and StringField?

#

in flask

magic palm
#

Can you use document.getElementById in a py file?

mental summit
finite laurel
#

I wish to use an npm package but my app is on a flask server. Can anybody help?

native tide
#

.help

glacial portal
#

I'm working on a flask project with 2 other people what should we do first the front end or backend?

rotund perch
#

is it possible to translate django responses on rest framework? (multi-language responses)

lyric parrot
#

so when i try to run the code it says no module named flask, i tried to change python interpreter but its not working anyone have an idea that might work?

whole garnet
#

which is better flask or django to pursue a career

whole garnet
#

u have initialize an app like

#

app = Flask(

#

name)

lyric parrot
#

oh

whole garnet
#

yeh

lyric parrot
#

let me try

whole garnet
#

from flask import Flask

#

and then

#

app = Flask(name)

#

__name __

#

underscore2nameundeerscore2

#

omg

#

wtf

#

--name--

#

instead of -- __

native tide
#

name

whole garnet
#

yah

#

see

#

lol

native tide
#

ez

lyric parrot
whole garnet
#

install flask

lyric parrot
#

i did

whole garnet
#

pip3 install flask

#

off

#

ohh

native tide
#

Grammar noob

lyric parrot
#

its still not workinh

#

g

native tide
#

Flask not flask

#

case sensitive

#

I think lol

whole garnet
#

no dude

#

it is flask

#

and Flask

native tide
#

Flask

whole garnet
#

yeh

#

app = Flask(--name--)

native tide
#

idk bro vsc sucks

#

undefined doesnt matter

#

if works

whole garnet
#

from flask import Flask

native tide
#

ignore undefined

#

doesnt matter if works

lyric parrot
#

cant

hollow minnow
whole garnet
#

remove
app = Flask(name) from function

native tide
#

ignore shitty vsc errors then

whole garnet
#

lol

lyric parrot
whole garnet
#

sometimes i forget to put @ and stare at the code for hours

#

ohh

#

send error ss

valid dawn
#

I was curious if whether having cloud serve act as my database for the iot system can affect the system's performance?

#

because I was using mongodb, but only realized that it can only store the images in a string type unlike cloud server which you can see the images taken from the iot directly from the server.

glad patrol
#

Can someone help regarding php laraval

thorn lily
#

It's better to ask in a php server

manic garnet
#

a poll

#

Django vs php

#

which is good for web dev

serene prawn
#

It depends

stark tartan
stark tartan
manic garnet
#

well yeah i used django

#

and then used php

robust folio
#

hey

#

is there anything like one click and hacked, and can anyone explain me about it?

manic garnet
#

bruh

robust folio
manic garnet
#

yes

robust folio
#

ohh ok

manic garnet
#

what do u want to know bout one click and hacked

#

like what r u even talking bout

robust folio
#

i wann a know how it works

#

and what is it

#

which tool to use

#

everything

manic garnet
#

there is no tool for that

robust folio
manic garnet
#

u gotta know ethical hacking and cybersec stuff to setup your own tools

robust folio
manic garnet
manic garnet
robust folio
#

no dont need to explain every thing

#

jst important points

manic garnet
#

it ain't working that way

#

u have to learn it in detail

robust folio
#

jst tell me surfacely

manic garnet
#

as far as I think u r trying to phish someone and kid this ain't the place to talk hacking stuff

#

don't send me reqs

robust folio
manic garnet
#

no i don't accept strangers reqs

robust folio
#

ok

manic garnet
#

u gotta search on the topic

robust folio
#

anyways its web development

manic garnet
#

and learn with a structure

robust folio
#

so i came here

#

to get some knowledge abt it

manic garnet
robust folio
# manic garnet tell me what u did

i searched but, what I found was there is like the victim(who is going to be hacked ) should also provide
authentication to get hacked

#

and i wanna know can some one get hacked by just clickng a link

manic garnet
#

yes they can btw

wheat verge
#

how to deploy django app the easiest way?

manic garnet
wheat verge
#

and why cant we deploy it in netlify?

manic garnet
robust folio
manic garnet
wheat verge
manic garnet
#

idk if they are available on github or not

robust folio
manic garnet
#

I don't remember the name I'm not a cybersec guy

#

but u can use it to clone webpages and host it

#

just like make a fake LinkedIn page and host it

#

And send it to someone and if someone enters their credentials to login u get what they entered which is the their credentials

robust folio
#

everyone is aware of it

#

and i was taking abt hacking systems not linkden acc

manic garnet
#

it's hacking bruh

#

it was an example man

robust folio
#

ik it

manic garnet
#

it's kind of not easy to hack into systems

#

u have to either setup a malware or a backdoor u developed physically in a system and get access

robust folio
#

i jst wanna know is how is it possible to get hacked by jst clicking to link and not doing any thing else

manic garnet
#

it ain't possible

#

it is never possible

#

unless ur very trained and can code tools that can make this possible

robust folio
#

it was about RAT link

manic garnet
#

if yes then do what it says

#

u still will have to get the malware in the victim's phone somehow

#

and if it is successful u have the access to the system

robust folio
#

it was like getting a malware in browser and if victim closes the browser then u will be no longer getting information

manic garnet
#

idk bout that bruh

robust folio
#

its form quora

manic garnet
#

u read the edit part

robust folio
#

but it is possible he said

violet mesa
wild iron
#

I made this basic thing