#web-development

2 messages · Page 128 of 1

plain zealot
#

html
{
min-height:100%;
}

html, body
{

  object-fit: cover;
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 0px;

}

#

@austere cloud

#

This is my HTML and css in part

#

I used this in my last project and it worked perfectly fine

native tide
#

any1 use selenium

#

i need help

mortal mango
#

how do I make a button in an html template trigger a view?

silk brook
#

Hey so I'm currently using Flask to create a website, and I can't add images to my website. Anyone knows how to fix that?

lucid vine
#

anyone knows if it is possible to change order of attributes inside a pydantic model after they have been defined?

silk brook
wicked elbow
#

whats returned after a delete in django?

#
class MembersDeleteApi(generics.GenericAPIView):
    permission_classes = [
        permissions.IsAuthenticated
    ]
    serializer_class = MembersSerializer

    def delete(self, request, pk):
        member = Members.objects.filter(pk=pk)
        member.delete()
        queryset = Members.objects.all()
        return Response(MembersSerializer(queryset))

is this setup right?

heady stream
#

hey guys, i know django has its own forums where you can ask django related questions and get answers in no time!
Does flask have the same thing?
I searched online for it and couldn't find it!

native tide
#

Hey, looking at developing APIs, how can I go about this?

amber horizon
#

and it uses Postman for testing

native tide
#

Has anyone worked with DRF deserialization? What exactly does this mean?

Deserialization is similar. First we parse a stream into Python native datatypes...

import io
from rest_framework.parsers import JSONParser

stream = io.BytesIO(json)
data = JSONParser().parse(stream)
vestal hound
#

what deserialisation is?

native tide
#

Well, yeah, specifically what this is:
stream = io.BytesIO(json)

vestal hound
#

BytesIO wraps a bytestring object

#

and turns it into a stream

#

you can think of it as mimicking the effect of opening a file in binary mode

#

except the data comes from the object you pass instead of a file

native tide
vestal hound
#

actually I think it's called a bytes object

#

can't really remember

#

something like that

native tide
vestal hound
#

!e print(b'abc')

lavish prismBOT
#

@vestal hound :white_check_mark: Your eval job has completed with return code 0.

b'abc'
vestal hound
#

!e print(type(b'abc'))

lavish prismBOT
#

@vestal hound :white_check_mark: Your eval job has completed with return code 0.

<class 'bytes'>
native tide
#

oh wow, never knew about that one

static cairn
#

Hello all. I have a number of Python automation scripts that I would like to "host" on a web server for others to use on my company's internal network. All I need is a way to have the scripts passed data entered by a user on a web page and then output data to that same webpage after the script runs. I am googling around and finding flask, django, cgi, etc... and getting overwhelmed by the options. Can anyone point me in the right direction? I'm wanting to do this with Apache on a RHEL server. DMs are welcome.

native tide
#

io.BytesIO(json) what's with the json in the parenthesis?

vestal hound
vestal hound
native tide
#

hmm man, i barely know about bits/bytes and what have you

vestal hound
#

a string

native tide
#

and does the stream have any significance? why would it mean by that

static cairn
vestal hound
#

consists of bytes and an encoding

#

because the same byte can mean different things in different encodings

#

so a byte is basically encoding-agnostic (BASICALLY)

#

and bytes are what is sent over HTTP

#

you don't really need to know the details

#

but you can basically think of bytes as raw data and the process of deserialisation as one that turns that raw data into Python objects

vestal hound
#

since this is a Python server

#

you can look at Flask or Django

#

a web framework maps routes (URLs, basically) to code (Python functions, in this case)

#

so you would have a route that, when accessed, takes some data, processes it, and returns a page with the results

#

you can look into DJango

static cairn
vestal hound
#

yw

native tide
vestal hound
#

it's the other way round

#

bytes are serialised data

#

the json

native tide
#

hollup, deserialization is python -> json?

vestal hound
#

no

#

that's serialisation

native tide
#

so if I sent over json to my api, that's already a byte object? because everything sent over in requests is in bytes?

#

as in the "raw data"

vestal hound
#

so if I sent over json to my api, that's already a byte object? because everything sent over in requests is in bytes?
@native tide ...yes, but you probably shouldn’t be dealing with that directly

#

since you’re using DRF

native tide
#

yeah DRF serializers have been doing deserialization, I was just confused on that part of the drf docs

#

oh yeah i found what answers the question before

#
json = JSONRenderer().render(serializer.data)
json
# b'{"email":"leila@example.com","content":"foo bar","created":"2016-01-27T15:17:10.375877"}'
#

so yeah json is a bytes object

edgy isle
manic sage
#

!e print('lool')

lavish prismBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

plain zealot
#

Anyone know how can I make the change here (the description under google search result)? Built it in react btw

versed python
coral raven
#

Open the index.html file and see for that statement in the head tag and replace

twilit needle
#

I have this django constraint

class Invite(BaseModel):
    class Meta:
        verbose_name = 'invite'
        verbose_name_plural = 'invites'
        # we need an index around the invite's created_at
        # column because we don't actually delete
        # expired invites from the database
        indexes = [
            models.Index(fields=['owner'], name='invite_owner_idx'),
            models.Index(fields=['box'], name='parent_box_idx'),
            models.Index(fields=['created_at', 'pk_id'], name='pk_created_at_idx'),
        ]
        constraints = [
            models.CheckConstraint(
                check=(
                    models.Q(expires_at__isnull=True) |
                    models.Q(expires_at__range=[models.F('created_at'), models.F('created_at') + timedelta(hours=48)])
                ),
                name='expires_at_datetime_check',
            )
        ]
#

however the second one doesnt work

#

I guess am not using the F datetime and timedelta functions properly

#

can someone please help me with that?

#

pls ping when help, thanks a lot!

plain zealot
native tide
#

if I am aiming for front-end development, where should I start?

wet light
#

hii guys sorry im a newbie in flask , how do i use flask and push the items over to html?

ashen spire
#

What framework/toolchain do you use for web development (front/back end or fullstack) and why? I'm looking to get into this, and I basically know that Django and flask exist, and that's about it. Difficulty is of little relevance to me, I'll learn anything.

honest dock
#

Django question:
Is there any way I can filter something like this:
Author = [1,2,3,4]
Book.objects.filter(user__pk=author)?

deft knot
#

@honest dock Book.objects.filter(user__pk__in=author)

wet light
shadow dirge
#

you have to use jinja to represent the data

#

and pass any data through render_template

wet light
#

oh so its something like this ?

#
      <tr>
        <td>{{ ingredient.getName() }}</td>
        <td>{{ ingredient.getAmount()}}</td>
        <td>{{ ingredient.getCost()}}</td>
</tr>
{%endfor%}
{%endblock%}```
shadow dirge
#

yes

#

pass the ingredients list inside render_template

honest dock
wet light
shadow dirge
wet light
#

oh

lyric jacinth
#

hello guys I got some basic code with flask for a little webapp. Anyone wanna help to make something bigger out of it?

meager bridge
#

we should debug the sdt module so we can access the basedata

#

right?

wicked elbow
#
#Serializer
fields = ['id', 'post_id', 'user_liked', 'timestamp']

but when i query its not giving me the id... anyone know why?

wicked elbow
#
# Serializer
class LikeSerializer(serializers.ModelSerializer):
  post_id = serializers.SlugRelatedField(
    many=False,
    read_only=True,
    slug_field='id'
  )
  user_liked = serializers.SlugRelatedField(
    many=False,
    read_only=True,
    slug_field='username'
  )

  class Meta:
    model = Likes
    fields = '__all__'

#API
class LikesApi(viewsets.ModelViewSet):
  permission_classes = [
    permissions.IsAuthenticated
  ]
  serializer_class = LikeSerializer
  queryset = Likes.objects.all()

why isnt it returning the id. not getting it front end, and not getting it in postman... i dont understand

glossy arrow
#

Hey guys, I have two tr elements inside a table, the first one toggles the other, sorta like a collapse, but it won't work, any idea why?

#

I have something like ```jinja
<tr>
<td>
<h1> Title </h1>
<a data-toggle="collapse" href="#userTable"><i class="fa fa-chevron-down"></i></a>
</td>
</tr>
<tr>
<div class="accordion-body collapse" id="userTable">
<td>
<h1> Test </h1>
</td>
</div>
</tr>

#

This is inside a table

native tide
sleek tapir
#

anyone here know JS reduce function and how to implement?

teal needle
native tide
#

what

#

you sir are smart

teal needle
#

just good eyes

#

Reading Is Fundamental.

wicked elbow
#

anyone know how to not have 7000 if statements in my get_queryset() for filtering? its getting a little out of hand

teal needle
#

@wicked elbow can you share a snippet to demonstrate what you're talking about?

wicked elbow
#

its pretty excessive... i can think of a couple things to shrink it a tiny bit

#

its super ugly too. i understand it, but i doubt everyone does

wicked elbow
#

wooh im so close to this project to be finished! just have to set up the search and do a put request for the settings page and its all done at least all the hard stuff

lavish prismBOT
#

Hey @native tide!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

native tide
#

help

wicked elbow
#

are you running in a virtual environment?

native tide
wicked elbow
#

well if you are using in a virtual env make sure its running before using it... ive only ever used npm in pipenv shell

#

im sure it could be used without the virtual enviroment, but thats what you could be missing. i dont know that specific package your installing so cant really help, just my two cents

mortal mango
#

is there a way to make a view to do an HttpResponseRedirect() without a render() in django?

teal needle
wicked elbow
plain haven
#

Though this may not be the best place to ask but what is better for web-scraping scrapy or selenium and if possible can someone explain it to me

native tide
wicked elbow
# native tide im not using py im using js

Yea, you can use python to create a virtual environment for it. Dont actually have to use python other then for the virtual environment. Is your package.json setup correctly? Theres a million things that could be your issue. Google specifics about your problem. Very little we can tell from your error log.

mortal mango
#

Reverse for '<QuerySet [<ShortURL: https://google.com>]>' not found. '<QuerySet [<ShortURL: https://google.com>]>' is not a valid view function or pattern name.

def page_redirect(request, url):
    get_url = ShortURL.objects.filter(short_url=url)
    return redirect(get_url)
```How would I filter out the QuerySet so I can get a string with `https://google.com` inside it?
scarlet latch
#

If Heroku is bad, according to many people on this server, what is better to use?

#

I tried AWS and Firebase, but they are complicated and it didn't work in the end

#

And I am having a problem with Heroku sessions that I put into #help-lemon if anyone knows how to answer it

#

Thanks!

vestal hound
#

If Heroku is bad, according to many people on this server, what is better to use?
@scarlet latch why do they say it’s bad

scarlet latch
#

Not sure

vestal hound
#

Not sure
@scarlet latch if you are just starting out, honestly, it doesn’t really matter IMO

scarlet latch
#

Could you try to help?

#

Thanks!

vestal hound
#

Could you try to help?
@scarlet latch what database are you using

#

with Flask for season storage

scarlet latch
#

It is hosted on Heroku

#

PostgreSQL

vestal hound
#

I would start with checks on the database to see if sessions are getting validated somehow

scarlet latch
#

I see the session variable gets created

#

In Chrome dev tools

#

But most of the time it gets cleared on the redirect

#

And when I check if the user is logged in, when the session variable is cleared, I see that they aren't logged in

#

But they should be logged in

glad patrol
#

hi

#

i have a html form which require use registration

stark storm
#

Anyone help me with flask? I need to save some data submitted to me in json format by user. Currently I am saving it as follows

# get json data in the request
req_data = request.get_json()
#session['data'] is initialised as a list
data = session['data']
data.append(req_data)
session['data'] = data

Is there a better way to do this ?

unique ore
#

i am starting to learn django
any suggestions where i can learn it from?

#

do i have to install virtual env?

plain zealot
#

Has anyone ever publish chrome extensions?

#

I have a question

stark storm
unique ore
#

Playing with the API¶
Now, let’s hop into the interactive Python shell and play around with the free API Django gives you. To invoke the Python shell, use this command:

/ 
$ python manage.py shell
We’re using this instead of simply typing “python”, because manage.py sets the DJANGO_SETTINGS_MODULE environment variable, which gives Django the Python import path to your mysite/settings.py file.

Once you’re in the shell, explore the database API:

from polls.models import Choice, Question # Import the model classes we just wrote.

No questions are in the system yet.

Question.objects.all()
<QuerySet []>

Create a new Question.

Support

#

this is what i found on a tutorial

#

where do i need to write the code exactly

#

🥺

native tide
# unique ore 🥺

When you see $ before the command, that is the terminal, when you see >>> that is the python shell

unique ore
#

o

#

but

#

it also has from polls.models import choice where do i type it @native tide

native tide
#

it's python, the only place you can type that is the python shell

unique ore
#

ok

#

ok

#

got it

young oak
unique ore
#

sure

#

i mean i just saw a tutorial and it didnt use virtaul env lol

#

it was to create a poll

young oak
native tide
#

good luck guys 🙂 @young oak @unique ore

young oak
unique ore
#

tysm

#

can u tell the pattern u used @young oak by far

young oak
#

so for me I started with the docs file of Django, and if i dont understand, i go to youtube to see a visual represntation of how things are done .

unique ore
#

ohk

bitter trail
#

I have 2 websites.
1 website is made in php with dotnet.
The other one is made with django and react.
These 2 have separate database.
Each site dashboard has an option to go over the other website.

What I want to do is whenever a user login in one of the website , and click on the link to go to the other site.
User doesn't have to login again in the 2nd site...

As in I want to create a single sign on.
Can someone guide me from where to start.

native tide
#

can someone explain to me the Debug=True Variable in Flask? I have a problem with flask_talisman. In development i have Debug=True and because of that flask talisman does not force SSL and i can test locally on 127.0.0.1:5000. When I push to server I set Debug to False, right? When I do this, I cannot test locally, because flask talisman forces SSL - understandably. But when I change Debug back to True I still cannot test locally and SSL is still forced

#

why is it like that?

lyric jacinth
#

Which env are you using?

native tide
#

i user virtualenv and simply set if __name__ == '__main__': app.run(debug=True)

lyric jacinth
#

I have difficulties in using dunder here, it says that name is not defined

#

name*

turbid axle
#

how to webscrape the css elements in a webpage using BeautifulSoup??

slim python
#

Can anyone help me with Django? I have a webapp deployed in production, but when I change the templates(HTML) it wont load the changes...
What I tried:

  • reloading Nginx
  • reloading supervisor (i have gunicorn there)
coarse skiff
#

hi am new to python i need help

scenic vapor
#

Hello friends i have a quick question for APIs.

#

One of API calls is a web scraper and it has multiple steps

#

how can i return a message after every step?

wicked elbow
mortal mango
#

I know that if you overuse html meta redirects, google can detect your website as spam and remove it from their index. Is this the same with django shortcut redirects?

untold flare
#

How would I connect fastapi with asyncpg?

quick cargo
#

make a connection pool

#

attack it to the app or vice versa

#

make the pool useing the startup event which is called when the loop is first started

untold flare
#
import asyncpg
from fastapi import FastAPI


app = FastAPI()
database = None

@app.on_event("startup")
async def startup_event():
  credentials = {"user": "foo", "password": "foo", "database": "foo", "host": "127.0.0.1", "port": "5432"}
  database = await asyncpg.create_pool(**credentials)

@app.get("/")
async def root():
    return {"id": database.fetch("SELECT * FROM bar WHERE id = 1")["id"]} # this will always return 1, just an example for question

Like this?

untold flare
lyric jacinth
#

What does your above code does?

untold flare
#

It's an example fastapi setup, I was asking ハーリさん (CF8) how to setup asyncpg (async python database interface) with fastapi (python api generator) :D

lyric jacinth
#

ah!

#

hey could you help me with my code?

lavish prismBOT
lyric jacinth
#

from flask import Flask, render_template, request
from vsearch import search4letters
app = Flask('name')

def log_request(req: 'flask_request', res:str) -> None:
with open('vsearch.log','a') as log:
print(req, res, file=log)

@app.route('/search4', methods=['POST'])
def do_search() -> 'html':
phrase = request.form['phrase']
letters = request.form['letters']
title = 'Here are your results:'
results = str(search4letters(phrase, letters))
log_request(request, results)
return render_template('results.html',the_title=title, the_phrase=phrase,
the_letters=letters, the_results=results)

@app.route('/')
def entry_page() -> 'html':
return render_template('entry.html', the_title='Welcome to search4letter on the web!')

@app.route('/viewlog')
def view_the_log() -> str:
with open('vsearch.log','a') as log:
contents = log.read()
return (contents)

app.run(debug=True)

untold flare
#

!codeblock

lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

untold flare
#

You can format the the code using the above ^

#

Unfortunately, I don't know much about flask

lyric jacinth
#

!codeblock

untold flare
#

Also make sure to include your question :D

slim python
#

Hey ! Do you know about django? Very basic django?

lyric jacinth
untold flare
#

Here, I'll just format it for you

#

Not my code, I formatted this for @lyric jacinth.

from flask import Flask, render_template, request
from vsearch import search4letters
app = Flask('name')

def log_request(req: 'flask_request', res:str) -> None:
    with open('vsearch.log','a') as log:
        print(req, res, file=log)

@app.route('/search4', methods=['POST'])
def do_search() -> 'html':
    phrase = request.form['phrase']
    letters = request.form['letters']
    title = 'Here are your results:'
    results = str(search4letters(phrase, letters))
    log_request(request, results)
    return render_template('results.html',the_title=title, the_phrase=phrase, 
                           the_letters=letters, the_results=results)

@app.route('/')
def entry_page() -> 'html':
    return render_template('entry.html', the_title='Welcome to search4letter on the web!')

@app.route('/viewlog')
def view_the_log() -> str:
    with open('vsearch.log','a') as log:
        contents = log.read()
    return (contents)

app.run(debug=True)
lyric jacinth
#

thanks!! How did you do it?

untold flare
#

```py
code goes here
```

#

When you do that:

print("Hello")
#

It gives code highlighting and a helpful indentation :D

lyric jacinth
#

'''py

untold flare
#

It's actually backticks, not quotes

lyric jacinth
#

how to change the line?

#

when i press enter it just sends the message

untold flare
#

Shift+Enter

#

a
b

lyric jacinth
#

oh thank you so much!!

lyric jacinth
lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

lyric jacinth
#
from flask import Flask, render_template, request
from vsearch import search4letters
app = Flask('name')

def log_request(req: 'flask_request', res:str) -> None:
    with open('vsearch.log','a') as log:
        print(req, res, file=log)

@app.route('/search4', methods=['POST'])
def do_search() -> 'html':
    phrase = request.form['phrase']
    letters = request.form['letters']
    title = 'Here are your results:'
    results = str(search4letters(phrase, letters))
    log_request(request, results)
    return render_template('results.html',the_title=title, the_phrase=phrase, 
                           the_letters=letters, the_results=results)
    
@app.route('/')
def entry_page() -> 'html':
    return render_template('entry.html', the_title='Welcome to search4letter on the web!')

@app.route('/viewlog')
def view_the_log() -> str:
    with open('vsearch.log','a') as log:
        contents = log.read()
    return (contents)

app.run(debug=True)

the log_request function is suppose to create a log file(vsearch.log) but instead it creates a text file(vsearch.txt). Can someone figure out what's the deal here?

quick cargo
slim python
#

I could use some help with django templates! I change the html code but the changes wont refresh on the site

slim python
#

Yes... I'm a bit lost...

nimble epoch
#

ok whats wrong?

slim python
#

I made changes to a template that i extend, but I'm having issues because the changes dont show on the website

#

I use:

  • venv
    -nginx
    -supervisor with gunicorn
nimble epoch
#

is it deployed?

slim python
#

Yes

nimble epoch
#

maybe the debug mode is off

#

isnt it?

slim python
#

Debug is false, yes

nimble epoch
#

and of course if its deployed you have to add and commit changes if its like heroku

#

add and commit changes to github

slim python
#

I dont use heroku, my app is hosted on AWS manually

nimble epoch
#

did you init any github repo?

slim python
#

I'm using my own github

nimble epoch
#

so in your app directory where your app is type git status

#

what shown?

slim python
#

That my branch is up to date

nimble epoch
#

did you commit your changes

slim python
#

Yes

nimble epoch
#

did you push

#

?

slim python
#

Yep

nimble epoch
#

i hope its how i think

peak bronze
#

made by the same people who created starlette

#

which fastapi uses under the hood

#

as the web server
(also sorry for the ping in the reply, forgot to turn it off lol)

nimble epoch
broken abyss
#

Is there any trick to use django and venv?

#

i have created few small projects before

#

and I never had issue with ModuleNotFoundError: No module named 'searchtime'

#

this time I'm using venv (activated)

slim python
#

@nimble epoch done it! It was something related to messed up versions on my git, thank you for pointing me in that direction!!

slim python
broken abyss
#

I have created application with django-admin

#

added it to installed_apps

#

same way as I always did

untold flare
# quick cargo yes that would work, however i would recommend subclassing the FastAPI class and...

Are you saying like this?

class App(FastAPI):
  def __init__(self, *args, **kwargs):
    self.database = None
    super().__init__(*args, **kwargs)


app = App()

@app.on_event("startup")
async def startup_event():
  credentials = {"user": "foo", "password": "foo", "database": "foo", "host": "127.0.0.1", "port": "5432"}
  app.database = await asyncpg.create_pool(**credentials)

@app.get("/")
async def root():
  res = await app.database.fetchrow("SELECT * FROM bar WHERE id = 1")["id"]} # this will always return 1, just an example for question
  return {"id": res["id"]}

Couldn't I do the same without subclassing FastAPI? So, everything is the same except I remove the class and app = FastAPI().

quick cargo
nocturne jetty
#

!warn @strange gorge don't post ads/scams whatever that was.

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied warning to @strange gorge.

patent ingot
#

Hello, I would like to ask for Django, my models.py is:

# Tag
class Tag(models.Model):
    name = models.ManyToManyField(Translation, related_name='tag_name')

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

# Language
class Language(models.Model):
    name = models.CharField(max_length=420)
    abbreviation = models.CharField(max_length=420)


# Translation
class Translation(models.Model):
    text = models.CharField(max_length=420)
    language_id = models.ForeignKey(Language, on_delete=models.CASCADE)
#

The models.py is only a snippet of code. I think I made the right copy and paste for you.

jolly lily
#

can someone help me with this error : File "/app/by_page.py", line 318, in bypage plt.imshow(wordcloud, interpolation='bilinear') File "/usr/local/lib/python3.6/dist-packages/matplotlib/pyplot.py", line 2731, in imshow sci(__ret) File "/usr/local/lib/python3.6/dist-packages/matplotlib/pyplot.py", line 3102, in sci return gca()._sci(im) File "/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py", line 1856, in _sci raise ValueError("Argument must be an image, collection, or " ValueError: Argument must be an image, collection, or ContourSet in this Axes

#

this is line 318 plt.figure(figsize=(10,5))

#

im trying to upload a wordcloud

patent ingot
#

My views.py:

def default_similarity_call(item, search_string,  tags, and_or):
    tmp = item.objects.\
        annotate(tagsagg=StringAgg('tags__tag_name', delimiter=', ', ordering='tags__tag_name')).\
        annotate(
            distance=TrigramSimilarity('name', V(search_string)) + TrigramSimilarity('tagsagg', V(search_string))).\
        filter(distance__gte=0.2)

    if len(tags) > 0:
        query = Q(tagsagg__contains=tags[0])
        for i in range(1,len(tags)):
            if and_or == "and":
                query = Q(Q(tagsagg__contains=tags[i]) & query)
            elif and_or == "or":
                query = Q(Q(tagsagg__contains=tags[i]) | query)
        tmp = tmp.filter(query)
    return [(item.distance, model_to_dict(item), item.tagsagg) for item in tmp]
heady stream
#

flask question:
Is there a way I can get the terminal output and display it for the user in the front-end(UI)
for example, in my webapp, when I click run on the site, a certain output is displayed in the terminal
my questions is: can I get this result to display for the user to see?
Ik this is a weird question, but it would make my site more user friendly believe it or not!

vestal hound
#

you need to redirect stdout

#

also, you need a way for the server to send data

#

so either WebSockets or SSE

#

or some sort of polling

lofty cave
native tide
lofty cave
vestal hound
lofty cave
lofty cave
lofty cave
#

any recommendations ?

willow iron
#

hey does anyone know how to fix a dependency management issue with pipenv?

#

I'm trying to install Twilio but it conflicts PyJWT with social_auth_django

#

this is my pipenv graph : ( only included the part where problems are quite evident )

social-auth-app-django==4.0.0
  - six [required: Any, installed: 1.15.0]
  - social-auth-core [required: >=3.3.0, installed: 4.0.3]
    - cryptography [required: >=1.4, installed: 3.3.1]
      - cffi [required: >=1.12, installed: 1.14.4]
        - pycparser [required: Any, installed: 2.20]
      - six [required: >=1.4.1, installed: 1.15.0]
    - defusedxml [required: >=0.5.0rc1, installed: 0.6.0]
    - oauthlib [required: >=1.0.3, installed: 3.1.0]
    - PyJWT [required: >=2.0.0, installed: 1.7.1]
    - python3-openid [required: >=3.0.10, installed: 3.2.0]
      - defusedxml [required: Any, installed: 0.6.0]
    - requests [required: >=2.9.1, installed: 2.25.1]
      - certifi [required: >=2017.4.17, installed: 2020.12.5]
      - chardet [required: >=3.0.2,<5, installed: 4.0.0]
      - idna [required: >=2.5,<3, installed: 2.10]
      - urllib3 [required: >=1.21.1,<1.27, installed: 1.26.2]
    - requests-oauthlib [required: >=0.6.1, installed: 1.3.0]
      - oauthlib [required: >=3.0.0, installed: 3.1.0]
      - requests [required: >=2.0.0, installed: 2.25.1]
        - certifi [required: >=2017.4.17, installed: 2020.12.5]
        - chardet [required: >=3.0.2,<5, installed: 4.0.0]
        - idna [required: >=2.5,<3, installed: 2.10]
        - urllib3 [required: >=1.21.1,<1.27, installed: 1.26.2]
twilio==6.51.0
  - PyJWT [required: ==1.7.1, installed: 1.7.1]
  - pytz [required: Any, installed: 2020.4]
  - requests [required: >=2.0.0, installed: 2.25.1]
    - certifi [required: >=2017.4.17, installed: 2020.12.5]
    - chardet [required: >=3.0.2,<5, installed: 4.0.0]
    - idna [required: >=2.5,<3, installed: 2.10]
    - urllib3 [required: >=1.21.1,<1.27, installed: 1.26.2]
  - six [required: Any, installed: 1.15.0]
#

but what do I do next? how do I resolve this issue?

lofty cave
lofty cave
vestal hound
#

no need to keep pinging people...

#

anyway

#

you need an import in your settings.py

quartz yacht
#

I’m running Django via docker-compose. When I use the dev compose file css works fine. When I use my prod compose file css stops working. All other static files (images etc) work fine but this does not. Any ideas what I’m doing wrong in prod?

quartz yacht
#

If I have h2 set to green h2 appears green with the dev file. When I deploy with prod file h2 is black.

vestal hound
#

are the CSS files actually loaded?

quartz yacht
#

I mean... css works in the dev file

#

So yes?

#

H2 appears green when I use the dev file to deploy, and nothing else changes besides a few security settings in the prod compose file

vestal hound
#

I mean

#

inspect the page in web console

#

check what files are loaded.

quartz yacht
#

Oh gotcha, thank you.

#

If they aren’t loading what setting might trigger them to not load? Any off the top idea?

vestal hound
#

well

#

beats me honestly

#

since you say other static stuff is loading

quartz yacht
#

Ok, lol. Thanks haha I’ll check the web console

native tide
peak kelp
#

cool

bitter trail
#

unless you give each user an auth token only they can use as their login im not sure there is a way honestly. completely different backends
@wicked elbow

found something called SAML. Might be implementing that.

timber prawn
#

just curious, anyone in here coming from drupal?

scenic vapor
#

Hello i made a mailing app(frontend)
how can i connect it to Outlook
is it possible

native tide
#

Check their api

#

Or google it there’s probably a video or a guide out there

glad patrol
#

hi

#

can we run flask app under djano app

#

or if my flask app run on 1st vm can my django app directly access to flask app index.html page ?

glad patrol
#

hi what is my app name is this mdd or disease-predictor-master

still jay
#

@glad patrol your project's name is mdd

glad patrol
#

but i am trying to link css with html page

#

like this

#
<html>
{% load static %}

<link rel="stylesheet" href="{% static 'style.css' %}" />```
#

its not working

#

my css is not linnking with html

still jay
#

i dont remember much of django now but did u set STATIC_URL ?

glad patrol
#
<html>
{% load static %}

<link rel="stylesheet" href="{% static 'style.css' %}" />

<body>
<div class="container">
<div class="row it">
<div class="col-sm-offset-1 col-sm-10" id="one">
<p>
Please upload documents only in 'pdf', 'docx', 'rtf', 'jpg', 'jpeg', 'png' & 'text' format.
</p><br>
<div class="row">
  <div class="col-sm-offset-4 col-sm-4 form-group">
    <h3 class="text-center">My Documents</h3>
  </div><!--form-group-->
</div><!--row-->
<div id="uploader">
<div class="row uploadDoc">
  <div class="col-sm-3">
    <div class="docErr">Please upload valid file</div><!--error-->
    <div class="fileUpload btn btn-orange">
      <img src="https://image.flaticon.com/icons/svg/136/136549.svg" class="icon">
      <span class="upl" id="upload">Upload document</span>
      <input type="file" class="upload up" id="up" onchange="readURL(this);" />
    </div><!-- btn-orange -->
  </div><!-- col-3 -->
  <div class="col-sm-8">
    <input type="text" class="form-control" name="" placeholder="Note">
  </div><!--col-8-->
  <div class="col-sm-1"><a class="btn-check"><i class="fa fa-times"></i></a></div><!-- col-1 -->
</div><!--row-->
</div><!--uploader-->
<div class="text-center">
<a class="btn btn-new"><i class="fa fa-plus"></i> Add new</a>
<a class="btn btn-next"><i class="fa fa-paper-plane"></i> Submit</a>
</div>
</div><!--one-->
</div><!-- row -->
</div><!-- container -->
</body>
</html>```
#

yes i set static url

#
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [
    'diseasepredictor/static',
]
still jay
#

inside your app create a static folder then create a folder with same name as your app

#

eg: abc/static/abc

glad patrol
#

i create

still jay
#

did it work ?

glad patrol
#

not working

#

its not getting the css file

#

is this correct

#
{% load static %}
<html>
<link rel="stylesheet" href="{% static 'style.css' %}" />```
still jay
#
{% load static %}
<html>
<link rel="stylesheet" href="{% static 'abc/style.css' %}" />```
#

abc is your app name

glad patrol
#

my app name is mdd or disease-predictor-master ?

#

"GET /static/mdd/style.css HTTP/1.1" 404 1663

still jay
#

you did not add the /css part

#

{% static 'blog/css/main.css' %}

glad patrol
#

i remove css folder

#

now my style.css in static folder

still jay
#

show me a tree structure of the whole project

#

tree projectname

glad patrol
#

ok

#
Folder PATH listing for volume New Volume
Volume serial number is 60C9-826F
E:.
├───.idea
│   └───inspectionProfiles
└───mdd
    ├───.idea
    │   └───inspectionProfiles
    └───mdd
        ├───.idea
        │   └───inspectionProfiles
        └───disease-predictor-master
            ├───diseasepredictor
            │   └───__pycache__
            ├───static
            ├───staticfiles
            └───templates
#

it gives me "GET /static/style.css HTTP/1.1" 404 1651

still jay
glad patrol
#

i write tree it gives me above output

still jay
#

then your not in the root

glad patrol
#

i am in the root of folder

still jay
#

here blog and main are "apps" where as hello is the project

glad patrol
#

pls dm me

mortal lark
#

guys what is the best framework for web development in python ?

lilac belfry
#

for aiohttp, how do i use a on_response_prepare handler and a middleware

#

trying to catch the http_exceptions.BadStatusLine whenever the api is called incorrectly with the wrong method (HTTPS)

patent ingot
#

Hello, I would like to ask, what does this line do:

annotate(tagsagg=StringAgg('tags__tag_name', delimiter=', ', ordering='tags__tag_name')).\

What is 'tags__tag_name?

#

According to the documentation:

 class StringAgg(expression, delimiter, distinct=False, filter=None, ordering=())¶

    Returns the input values concatenated into a string, separated by the delimiter string.

    delimiter¶
#

It's expression

twilit needle
#

can someone please help me here?

#

thanks a lot!

native tide
patent ingot
#

It seems I don't know much about Postman

twilit needle
#

can someone please help me

native tide
#

says it at the bottom

patent ingot
#

But I don't see any problem here.

turbid estuary
#

what is the use of role attribute in tags like <div class="navbar" role="navigation">?
Does it explain what that tag would do? kinda like its function/use/role?
tag me to notify please

twilit needle
#

in django the file isnt being encrypted before storage

class DefaultStorage(storage.FileSystemStorage):
    def __init__(self):
        super(DefaultStorage, self).__init__()
        self.encryptor = Fernet(settings.ENCRYPTION_KEY)

    def _save(self, name, content):
        encrypted = self.encryptor.encrypt(content.file.read())
        content.file.write(encrypted)
        print(content.file.read() == encrypted)
        return super(DefaultStorage, self)._save(name, content)

why?
the print statement also returns false
I think I am reading and writing the file wrongly. Can someone pls help me?

twilit needle
#

can someone please help me here too?

#

thanks a lot!

native tide
opal bramble
#

I’m learning Django now. I have basic knowledge of templates I wonder if I have to definitely use DjangoForms in real time apps. I’m learning Django to connect to React anyways. So I just wanted to get over with. what are the basic things I should learn?

blazing otter
opal bramble
pallid laurel
#

@opal bramble learn django rest you will get it

blazing otter
mortal lark
#

Django is kinda old don't you think? It's a very good framework but there is a lot more to work with like flask and fastAPI which I found much easier to work with

opal bramble
blazing otter
#

yes, Django seems to be in big demand.

opal bramble
blazing otter
#

yup, but really good and thorough. I am only on page 30! haha but plugging away

mortal lark
#

I am a newbie in programming and I learned to code with python and loved working with web frameworks , I worked with webpy which I found out it's not that popular, but I loved working with it and I learned alot, but I wanna to be able to work with other frameworks too, I think django is the first option , and secondly flask and fastAPI. is it good idea to work with all of them or just focus and master one of them ?

opal bramble
blazing otter
#

I found doing a flask project helped in learning django. I would not have wanted to start with django first, and that was just luck on my part.

#

yes, flask and django have much in common.

opal bramble
#

I would suggest CS50W. That's where I was introduced to Django. I loved the course. Try it out and decide for yourself.

mortal lark
vernal furnace
#

I have a navbar from bootstrap and I have it at the top

#

thing is when I extend the html base page(the one with the navbar code) to another html page

#

the navbar covers the content underit

#

how to change it so that the content will be automatically under the navbar

unique ore
#

i

distant charm
#

lol

craggy elbow
#

Hi guys! I've just found this server... Any Flask experts around?

jolly lily
#

hey guys

#

I am trying to make a wordcloud in my web app

#
                        img = io.BytesIO()
                        wordcloud = WordCloud(background_color='white', max_font_size = 100, width=600, height=300).generate(cloud_words)
                        plt.figure(figsize=(10,5), facecolor = None)
                        plt.imshow(wordcloud)
                        plt.axis("off")
                        plt.show()
                        plt.savefig(img, format='png')
                        plt.close()
                        img.seek(0)

                        cloud_url = base64.b64encode(img.getvalue()).decode()
                        plt.clf()
#

I do this and send cloud_url to my html template

#

it works sometimes and sometimes it gives an error

#

File "/app/by_page.py", line 318, in bypage
plt.imshow(wordcloud)

#

raise ValueError("Argument must be an image, collection, or "
ValueError: Argument must be an image, collection, or ContourSet in this Axes

#

im not exactly sure why, any ideas?

toxic flame
#

hi guys my static files aren't serving... They were working just a while ago.

I've done everything on the internet has provided.

Static root, url, dir, urlpaterns + , collectstatic. Any help would be great.

blazing otter
scarlet onyx
blazing otter
opal bramble
vital rapids
#

does anyone know how to hack in console and show correct answers in edupage test?

glass badger
#

Any specialists in Django help me out with a small function inside my model? #help-honey

native tide
#

Hi, I am passing blogs object from view to template, which is all blog objects from the model. In template file, I have looped over all blogs and implemented them in cards. However, I want to restrict the blog.description to some word limit to show them as snippet. But, doing <p>{{ blog.description[:140] }}</p> seems illegal in django template. how can I achieve what I am trying to do?

past cipher
#
{% if 'category' in request.path %}
                    {% for item in posts %}
                        <h3>{{item.category}}</h3>
                    {% endfor %}
                {% else %}
                    <h3>ALL POSTS</h3>
                {% endif %}

How to break a loop after the first item?

#

I need ot loop through it, but want to stop after the first item

honest dock
#

@past cipher

{% for item in posts|slice:":1" %}
past cipher
#

thanks @honest dock

honest dock
#

@past cipher no problem mate

boreal panther
#

has anyone done any webscraping or headless browsing on facebook?

#

I have a friend who posts like 8 posts a day, and I want to see something they posted six months ago

#

it would take me hours of scrolling to get there, but I'm wondering if I can make a python script that would just grab all of the may-june posts from their feed

indigo kettle
#

on the website you can filter by year and month

boreal panther
#

it looks like you can only do that for your own profile, not for your friends posts unless they posted on your wall

indigo kettle
#

I see it for my friends' posts but maybe it's a feature that is rolled out to some users and not others or something.
In any case, sure you can write a python script to do that. It could use selenium and like, scroll down the page forever or something janky like that.
I'm sure this kind of thing is against their tos though so tread carefully

lucid vine
#

Is using 64 characters to sign my JWT tokens an overkill?

daring tulip
#

hey guys i was wondering if anyone can help me setup a postgresql connection to my flask app

#

having some trouble

split steeple
lucid vine
fallen spoke
#

I am using drfsimplejwt and I'm wondering how often should I refresh the access and refresh tokens currently I have: 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=30), and 'REFRESH_TOKEN_LIFETIME': timedelta(hours=6). is that ok? what happens if both tokens expire while the user if offline? will they have to log in again next time they want to use the website? not sure if I should stick to JWTs or use another method of authentication. any help is appreciated

lucid vine
#

refresh token's should be used for longer

fallen spoke
#

like multiple days?

lucid vine
#

I have an endpoint where an user can give a valid access_token and get a new one, don't use refresh ones myself

#

but for example gmail's refresh tokens last until you change password

fallen spoke
lucid vine
#

no, jose

fallen spoke
lucid vine
#

nope, fastapi

#

but you can prob. use it in django just that I don't have experience with it

fallen spoke
#

oh I see, isn't it a security problem to have a refresh token that lasts very long?

lucid vine
#

probably, but the spec is complicated it really depends on the implementation

fallen spoke
lucid vine
#

I am very new as well, I am refactoring one of my API's to use JWT for the first time

fallen spoke
#

good luck with that btw 🙂

robust beacon
#

Hi Folks,

Coming from PHP background, been heavily using PHP frameworks with some orchestration (composer, etc) tools alongside with Docker.

I see some differences here and there but I find overall concepts are similar..

Just started learning Django today and I am trying to build some workflow similar to what I've been doing for a while.

  1. Dockerizing application
  2. Frontend layer (React, etc)
  3. Configuration Management

I think I figured out #1, and #2 but would like to get some help on #3 part. What is the Django/Python's idiomatic way of managing the configuration workflow? for example, dev vs staging(Prod), use of settings.py, SECRET KEY?, and etc...

Any help would be appreciated, of if you can direct me to the good online resource that would be wonderful!

Thanks!!

vestal hound
#

that imports from settings_dev and settings_prod depending on the situation

robust beacon
#

@vestal hound thanks, is that a module that I need to install?

vestal hound
#

no

#

those are other files

#

also in the project directory

robust beacon
#

ah, I see just different config in different files gotcah

#

so in your settings.py, add some checks to determine local vs stage, etc? yeah ?

indigo kettle
#

exactly, set some environment variables and load different configs for each one

robust beacon
#

Gotcha

#

as for SECRET_KEY, do you just inject it on build time? like pass in as a parameter?

#

i.e say if you have some sort of CI tool..

indigo kettle
#

personally I also have that as an environment variable

#

for CI, I don't think it matters if it's hard coded into the settings_ci.py file or whatever it is

robust beacon
#

makes sense, thank you I think I gotta start with settings.py file

indigo kettle
#

yeah, so if you set the DJANGO_SETTINGS_MODULE environment variable to project_name.settings_ci

#

I believe that will tell django to use the settings_ci.py file you create

#

for example

silver grail
#

Hello everyone, I was wondering if someone could assist me with my django project. I am attempting to implement the django rest framework, and have build a class. The goal is to take the input to api/tickers/<PK> (i.e PK = MSFT) and return intraday results from my other model

class TickersAPI(viewsets.ReadOnlyModelViewSet):
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    serializer_class = StockIntradayDataSerializer

    def get_queryset(self):
        item = self.kwargs.get('pk')
        ticker_obj = StockTickers.objects.filter(ticker=item).get()
        return StockIntradayData.objects.filter(owner=ticker_obj)

by going to api/tickers/MSFT the DRF gives me back a "detail": "Not found."

indigo kettle
#

is ticker the primary key?

#

maybe you want to do filter(id=item)?

#

you can also forego the separate queries by searching through the related field like

#
StockIntradayData.objects.filter(owner__id=item)
#

also I think there's a get_object method you want to override instead

#

but I'm not sure

silver grail
#

ticker is the only field in that model

class StockTickers(models.Model):
    ticker = models.CharField(max_length=5, blank=False, null=False, editable=True)

    class Meta:
        pass

    def __str__(self):
        return f'{self.ticker}'

which i am using to filter by name, I know its probably not the best, but its the most relatable way to get it, (at least human readable) idk... so we need to get that in order to get the id, since the objects in StockIntradayData are associated to the id of the named ticker. If that makes sense

#
class StockIntradayData(models.Model):
    owner = models.ForeignKey(StockTickers, on_delete=models.CASCADE)
    data_datetime = models.DateTimeField(auto_now=False, blank=False, null=False, editable=True)
    open_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    high_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    low_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    close_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    volume = models.IntegerField(blank=True, null=True)```
#

I had the get_object override working when I had it configured to just find the ID and Ticker in the StockTickers model, but the end goal here is to give tickers/MSFT or whatever ticker and get back a JSON list of intraday data (preferably even then more filtered based on other user information)

indigo kettle
#

what does the urls file for this look like?

#

I'm not super familiar with drf

silver grail
#
router = DefaultRouter()
router.register(r'tickers', TickersAPI, basename='TickersAPI')


urlpatterns = [
    path("trade/import", tradeImportView, name="import-view"),
    path("trade/", view=trade_list_page_view, name="trade-list"),
    path("trade/detail/<pk>/", view=trade_detail_page_view, name="trade-detail"),
    path("trade/edit/<pk>/", view=user_edit_trade_notes, name="trade-edit"),
    path("trade/detail/<opk>/execution/<pk>", execution_edit_view, name="execution-edit"),
    path("dashboard/", view=dashboard_page_view, name="dashboard"),
    path("journal/", view=journal_page_view, name="journal"),
    path("reports/", view=reports_page_view, name="reports"),
    path("dayProfitLossChart/", dayProfitLossChart, name="dayProfitLossChart"),
    path("oneminbarchart/s=<symbol>d=<trade_date>", oneminbarchart, name="oneminbarchart"),
    path("TestChart/s=<symbol>d=<trade_date>", TestChart, name="TestChart"),
    path('api/', include(router.urls)),
]
indigo kettle
#

but I'm guessing ticker/<pk> is expecting to return a single object

#

so is this view in the router.urls?

#

I'd like to see that urls file

silver grail
#

Well, DRF uses the routers, at least for class viewsets from what I am learning. Without that, I could do normal def / function based. but the routers are supposed to make it "scaleable" per say

indigo kettle
#

you may want to search with a query param instead like /api/tickers?ticker=MSFT

silver grail
#

api/ ^tickers/$ [name='TickersAPI-list']
api/ ^tickers.(?P<format>[a-z0-9]+)/?$ [name='TickersAPI-list']
api/ ^tickers/(?P<pk>[^/.]+)/$ [name='TickersAPI-detail']
api/ ^tickers/(?P<pk>[^/.]+).(?P<format>[a-z0-9]+)/?$ [name='TickersAPI-detail']
api/ ^$ [name='api-root']
api/ ^.(?P<format>[a-z0-9]+)/?$ [name='api-root']

indigo kettle
#

and then grab that out of the get_queryset method

silver grail
#

so I get that if I type api/asdasda or whatever, since the router dynamicalls generates the url paths for it

indigo kettle
#

right so the tickers/<pk> is internally calling get_object and returns a single thing

#

but you don't have a StockTicker with primary key = MSFT

#

so it returns not found

silver grail
#

thats why we get the ticker_obj too, and that is what the return should be using

#

I have most of the def I wrote gone, but saved this from it, if I hardcoded this, it worked and returned the JSON object of all the TSLA intraday data, but I am not trying to return the entire DB at once....

symbol = 'TSLA'
    ticker_obj = StockTickers.objects.filter(ticker=symbol).get()
    queryset = StockIntradayData.objects.filter(owner_id=ticker_obj).all()
    serializer = StockIntradayDataSerializer(queryset, many=True)
    return JsonResponse(serializer.data, safe=False)```
indigo kettle
#

you can try it like this

class TickersAPI(viewsets.ReadOnlyModelViewSet):
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    serializer_class = StockIntradayDataSerializer

    def get_queryset(self, *args, **kwargs):
        ticker = self.request.GET.get('ticker')
        qs = super().get_queryset(*args, **kwargs)
        if ticker:
            qs = qs.filter(owner_ticker=ticker)
        return qs

and then go to
/tickers?ticker=MSFT

silver grail
#

it adds the / when I try to go there.

indigo kettle
#

that's fine

silver grail
#

AssertionError: 'TickersAPI' should either include a querysetattribute, or override theget_queryset()method.

#

which I dont understand because we are overriding the method

indigo kettle
#

maybe super() isn't defined?

#
    def get_queryset(self, *args, **kwargs):
        ticker = self.request.GET.get('ticker')
        qs = StockIntradayData.objects.all()
        if ticker:
            qs = qs.filter(owner_ticker=ticker)
        return qs
#

I think it should be but we can just write in our queryset explicitly

silver grail
#

ValueError: Field 'id' expected a number but got 'MSFT'.

indigo kettle
#

huh

#

oh it should be double underscore here

#

owner__ticker

silver grail
#

ok

indigo kettle
#

but I don't know if that's the issue still

silver grail
indigo kettle
#

worked?

indigo kettle
#

nice!

silver grail
#

Now to just add more kwargs I guess

indigo kettle
#

yup so you can add whatever you want

#

to the query params

#

and just keep filtering/sorting in the get_queryset method

silver grail
#

The end goal here is for me to load a chart that has my trades, but a trade has multiple executions, i.e. I bought 2 shares and sold 2 shares an hour later, so I only want the intraday data for that day to plot on a chart, v.s. spending compute and DB query time pulling everything (as it does atm)

indigo kettle
#

so you'll be able to query with start and end times as well and filter your querysets with those start and end datetimes

silver grail
#

Thank you for your help @indigo kettle

indigo kettle
#

np!

lilac belfry
#

in aiohttp anyone know how to use on_response_prepare

#

for when someone uses like HTTPS on a HTTP API

iron beacon
#

hey everyone, anyone knows a way to make so only one validator of a Django Field is required?

native tide
#

what is flask used for in web dev

toxic flame
#

Hi guys so basically I have a problem. Currently the static files aren't serving, but a while ago it did. I tried everything I could find on the internet but no success. Any suggestions?

opal bramble
native tide
#

downloading a file from a server is a post request?

broken abyss
#

hello guys, i there any way in Django rest to serialize datetime object?

vestal hound
twilit needle
#

So guys I am trying to configure apache with django for production here.
However, I am not able to serve media files.
https://stackoverflow.com/questions/65807289/django-configure-apache-to-serve-media-and-static-files
can someone please help me on s.o.?
Thanks a lot for your time!

#

or here also, can someone please ping me when help?

void iris
#

How do i run my py script on my website with cgi

native tide
#

i can't get to upload files using flask restful to work

solar summit
#

How do I make this ? stuff with flask?
this is what i tried:

@app.route("/password?length=<nbytes>")
def password(nbytes:int):
    nbytes = request.args.get('length')
    password = secrets.token_urlsafe(int(nbytes))
    return jsonify({"password":password})

if you didn't get what i mean:
most of the people who make api's and stuff have routes like this /password?length=someint - here user can enter any integer they want. I know how to make dynamic url like this password/5 - where 5 is length but I have no idea about passing the length variable.
i get a 404 with the above written code

true scroll
#

That's a GET request with a query string

#

Those are the terms you want to google

#

You don't put it in the route

broken abyss
slate oak
#

I have this error:

#

Can someone help me please ?

silver grail
native tide
native tide
#

Hello. I just started making a website and could use a decent bit of help with one section I'm trying to implement. If anyone would be able to help me it would be more than appreciated.

sand salmon
#

hey does anyone know anything about bs4 and chromium that can help me with an SSL issue

#

it started to do this out of the blue, its been working before but its a web scraper and im wondering if something got updated and changed the SSL and now it wont work

lofty cave
#

can someone join me in help-aluminum. I have an issue with Django communicating to a postgresql database, i dont know why

silver grail
#

Anyone know how to reference a url from a Django Rest Framework router inside an HTML template?

i.e. {% url 'appname:api' arg1 arg2 %} ?

meager shore
#

How can i write a api/auth test in postman? I cant fix is

native tide
#

what's the issue?

meager shore
#

Error 500

native tide
#

Probably an issue with your view

#

NoneType object is not subscriptable

lament mason
#

https://stackoverflow.com/questions/57242789/websocket-connection-failed-error-during-websocket-handshake-unexpected-respon

i have the same problem as that guy but I don't get how did he resolve, the answer was ```
You are using a WebSocket client to connect to a Socket.IO server. Use a Socket.IO client and you will be fine. WebSocket is not the same as Socket.IO, the latter is implemented on top of WebSocket and uses a different protocol.

meager shore
#

Does anyone know a good website or youtube video where I can see how I can test my webshop login in postman?

native tide
meager shore
native tide
#

You can add your tokens/headers/whatever within postman

quick cargo
#

bro ngl its an issue with your server code rather than postman

#

postman is showing that your code is crashing

native tide
#

^

quick cargo
#

hence the 500

#

5xx codes are the server crashed

native tide
#

Plus you got the error NoneType object is not subscriptable

quick cargo
#

4xx codes are you fucked up

#

2xx codes are okay

#

3xx codes are yeet ya to somewhere else

vestal hound
quick cargo
#

on auto pilot

meager shore
#

Hmmmm okee thankyouu! Then I need to fix my code

minor horizon
#

In flask caching, how can I get the last updated time of a cached object?

silver grail
#

Hi all, I am having an issue with arguments in my django rest API. I am passing ?ticker=TSLA but I am getting back everything from the initial queryset, like the filter is not happening.

class TickersAPI(viewsets.ReadOnlyModelViewSet):
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    serializer_class = StockIntradayDataSerializer

    def get_queryset(self, *args, **kwargs):
        qs = StockIntradayData.objects.all()
        ticker = self.request.query_params.get('ticker', None)
        if ticker is not None:
            qs = qs.filter(owner__ticker=ticker)
            return qs

    def get(self, request, *args, **kwargs):
        return Response({'something': 'my custom JSON'})

    def list(self, request, *args, **kwargs):
        return_list = []
        ticker = self.request.query_params.get('ticker')
        print(ticker)
        qs = StockIntradayData.objects.all()
        print(qs)
        if ticker:
            qs.filter(owner__ticker=ticker)
            print(qs)
            for execution in qs:
                data_datetime = execution.data_datetime
                op = execution.open_price
                hp = execution.high_price
                lp = execution.low_price
                cp = execution.close_price
                data_dict = {
                    "x": data_datetime,
                    "y": [op, hp, lp, cp]
                    }
                return_list.append(data_dict)
        return Response(return_list)```
steady temple
#

is this the correct channel to ask for web scrapping?

zinc hill
#

@silver grail if ticker is not None:
qs = qs.filter(owner__ticker=ticker) does this do anything?

silver grail
#

1 sec, sorry was out

brisk temple
zinc hill
#

Well yes I would assume anything that related to Web can be asked here.

#

hiring someone? im not too sure

silver grail
#

@zinc hill it does the same thing still. i.e returning all the results in the formated response. i.e. I give ?ticker=TSLA and it gives back all objects for MSFT and TSLA (only two I have data for in the DB )

#

The first print(ticker) is printing a string as expected, but both print(qs) are showing the same output

zinc hill
#

what happened if you do
qs = qs.objects.filter(owner__ticker=ticker)

silver grail
#

AttributeError: 'QuerySet' object has no attribute 'objects'

zinc hill
#

oh sorry

#

i mean

#
qs = 
StockIntradayData.objects.filter(owner__ticker=ticker)
#

oh i guess it does work yourway i didnt know that

silver grail
#

just returns an empty list

#

I should note that the owner is tied to the Ticker string of ticker in another model. I.e. StockTickers has ticker = charfield where I store all the tickers and then the intraday results are ForeignKey'd to StockTickers

#

I figured that was more efficient than querying for a string every time. So that is where the owner__ticker comes in, although I am ignorant as to how it works

zinc hill
#

wait

#
   def get_queryset(self, *args, **kwargs):
        qs = StockIntradayData.objects.all()
        ticker = self.request.query_params.get('ticker', None)
        if ticker is not None:
            qs = qs.filter(owner__ticker=ticker)
        return qs

#

does this work?

#

@silver grail

silver grail
#

erm idk. It just yells at me if it is not there, basically neither the get)queryset or the list def are filtering as expected

zinc hill
#

wait whats the different between def list and def get_queryset?

silver grail
#

Nothing. But the rest framework breaks if I do not define a queryset anywhere

#

either via a queryset = StockIntradayData.objects.all()
or overriding the get_queryset function

zinc hill
#

ok can you comment your codes? and follow this code

silver grail
#

Ok

zinc hill
#
class TickersAPI(generics.ListAPIView):
    serializer_class = StockIntradayDataSerializer

    def get_queryset(self):
        """
        Optionally restricts the returned purchases to a given user,
        by filtering against a `username` query parameter in the URL.
        """
        queryset = StockIntradayData.objects.all()
        ticker= self.request.query_params.get('ticker', None)
        if ticker is not None:
            queryset = queryset.filter(owner__ticker=ticker)
        return queryset
#

this is just a piece of code from the doc

#

i just wanna see if it would work to begin with

silver grail
#

Same thing

zinc hill
#

sorry i made some mistake in that code

#

can u do it again

silver grail
#

hold on

zinc hill
#

or do you jumping in a call

#

i just wanna see those code

silver grail
#

yea we can call

#

Im going to try to replace the qs in the list with that as well

lean wolf
#

Hey guys, I have couple questions about Selenium.

Is this the right place to ask about it?

honest vine
#
Failed to execute 'evaluate' on 'Document': The string '//span[contains(translate(@title)='Dd')]' is not a valid XPath expression.

any solution?

turbid estuary
native tide
#

You can also do alert-sucess and it would give the alert a green colour

woeful atlas
#

Hello, I send a variable (connect) on my template with quart containing the status of the user and there puts in: <img src="{{ url_for('static', filename='assets/IconDiscord/{connect}.png')}}" but for some unknown reason, it modifies the name of the image by %7Bconnect%7D.png, so it doesn't find the image, do you have an idea how to fix this?

merry geyser
#

yo

#

can someone tell me

#

what is this

#

like what do we call it

#

this #document

#

its inside an iframe

#

i dont hve tht much experience in web dev

gaunt marlin
autumn hill
#

Hey need some help with python and regex

#

Im trying to split input string at \r\n and period followed by space but not after Mr/dr etc

vagrant owl
#

Hi all.
I've been using marshmallow for object serialization/deserialization and I came across this piece of code:
`
from marshmallow import fields, Schema

from encrypt import encrypt_pass

class UserSchema(Schema):
class Meta:
ordered = True

id = fields.Int(dump_only=True)
username = fields.Str(required=True)
password = fields.Str(required=True, deserialize='load_password')

def load_password(self, value):
    return encrypt_pass(value)

`
Now, I understand most of it but what does is the functionality of deserialize attribute inside fields.Str() apart from calling the function?

inland pecan
#

[FOR HIRE][REMOTE]
Hi, everyone.
How are you?

This is Lee from China.

https://www.linkedin.com/in/lminglai
https://liminglai.herokuapp.com

If you need a web developer please contact me.
I am well versed in

  • Express, Koa, Nest, Python/Django, PHP, Laravel, AWS
  • MongoDB, MySQL, SQLite
  • React, Next, Redux, FunctionalComponents, Hook, Thunk, Saga

I am available and can start work right now.
Thank you.

real hare
#

Hi, if you're passing a value from your front end to the backend of flask. Are you "grabbing" the name you've assigned to the originating source? E.g. a input field called name. So would just do request.form.name to retrieve that value?

turbid iron
untold flare
sage escarp
#

hi bois , i've never done web stuff before and i thought about automating some stuff around the house with python and a respberry pi. Everything would be controlled from a webpage that runs on the pi and my question is :if i make a script that let's say turns a lightbulb on and off and i want my page to have a button that triggers that script is it enough to make that button go to a non existen link and then in django rout it to a function that just triggers the scrip and then resets the current page would that work ?

woeful atlas
#

you know why the page loads infinitely (it freezes when it gets the info)

from quart import Quart

from discord.ext import ipc

app = Quart(__name__)
ipc_client = ipc.Client(secret_key="my_secret_key") # secret_key must be the same as your server

@app.before_first_request
async def before():
    app.ipc_node = await ipc_client.discover() # discover IPC Servers on your network

@app.route("/")
async def index():
    user = await app.ipc_node.request("get_user", user_id=640518207257444374)
    return user

if __name__ == "__main__":
    app.run()```

and api:
```py

import discord
from discord.ext import commands, ipc

class MyBot(commands.Bot):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.ipc = ipc.Server(self, "localhost", 8765, "my_secret_key") 
    
    async def on_ready(self):
        """Called upon the READY event"""
        print("Bot is ready.")
    
    async def on_ipc_ready(self):
        """Called upon the IPC Server being ready"""
        print("Ipc is ready.")

my_bot = MyBot(command_prefix="!", intents=discord.Intents.all())

@my_bot.ipc.route()
async def get_user(data):
    user = my_bot.get_user(data.user_id) 
    print(user)
    return user.name

if __name__ == "__main__":
    my_bot.ipc.start() # start the IPC Server
    my_bot.run("token")
mint tangle
#

Get request to my backend works but post fails

#

Here's the client side code sending the get request (it's in javascript)

#
axios
            .post(`http://127.0.0.1:5000/tags/`, {
              image: srcUrl
            })
            .then(function(response) {
              console.log(response);
            })
            .catch(function(error) {
              console.log(error);
            });
#

Here's the backend code

#
from imageai.Classification import ImageClassification
import os
from flask import Flask
app = Flask(__name__)


@app.route('/')
def hello_world():
    return {"What's": "up"}


@app.route('/tags')
def put_tags(image):
    execution_path = os.getcwd()

    prediction = ImageClassification()
    # prediction.setModelTypeAsResNet50()
    # prediction.setModelTypeAsInceptionV3()
    prediction.setModelTypeAsDenseNet121()

    prediction.setModelPath(os.path.join(
        execution_path, "DenseNet-BC-121-32.h5"))
    prediction.loadModel()

    predictions, probabilities = prediction.classifyImage(
        os.path.join(execution_path, image), result_count=5)

    final = []
    for eachPrediction, eachProbability in zip(predictions, probabilities):
        final.append(eachPrediction)

    response = Flask.jsonify({'tags': final})
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response
native tide
#

Hello. I just started making a website and could use a decent bit of help with one section I'm trying to implement. If anyone would be able to help me it would be more than appreciated.

agile shell
#

How can I use websockets for Flask?

untold flare
#

what's the best way to have a consistent aiohttp session in fastapi?'

quick cargo
untold flare
quick cargo
#

Sounds like you wanted something like my router system 🤣

#
class Authorization(router.Blueprint):
    def __init__(self, app: FastAPI):
        self.app = app

        self.app.on_event("startup")(self.init_session)
        self.app.on_event("shutdown")(self.close)

        self.session: t.Optional[aiohttp.ClientSession] = None

    async def init_session(self):
        self.session = aiohttp.ClientSession()

    async def close(self):
        if self.session is not None:
            await self.session.close()

    @router.endpoint(
        "/login",
        endpoint_name="Discord Login",
        description="Login via discord.",
        methods=["GET"],
    )
    async def login(self, request: Request):
      # ... stuff

#

This is what i ended up creating for my router

untold flare
#

Does that require a different instances for each file? Or did you just create an instance of said class which you import?

quick cargo
#

its actually pretty similar to the d.py cogs and extensions system

#

just made to be a universal router for my web apps

untold flare
#

I see, alright, thanks!

#

I'll see what I can do with that

quick cargo
#

So I thought I would share some interesting benchmarks we've found after building our own Bench marker designed to put frameworks under a more realistic load with some more features planned.

TL;DR: Uvicorn + X is definitely not the fastest server

We tested 2 Frameworks and 1 Server.

  • Sanic as it's framework and server.
  • FastAPI and Uvicorn as the server.

Interestingly Sanic is king when pipelining is not enabled.
Sanic overall seems to handle Non-Pipeline connections much better than Uvicorn does, Uvicorn's advantage on benchmarks like Tech Empower come from the fact Wrk is biased towards pipelined request and uvicorn although it does not directly pipeline concurrent buffers pipelines allowing it to appear to be handling more requests.

======= Uvicorn Raw =======
$ ./rewrk -h http://127.0.0.1:5000 -c 256 -t 12 -d 15s
Benchmarking 256 connections @ http://127.0.0.1:5000 for 15 seconds
  Latencies:
    min    - 8.47ms
    max    - 162.46ms
    median - 76.99ms
  Requests:
    Total Requests - 171180
    Requests/Sec   - 11372.99

======= Sanic =======
$ ./rewrk -h http://127.0.0.1:5001 -c 256 -t 12 -d 15s
Benchmarking 256 connections @ http://127.0.0.1:5001 for 15 seconds
  Latencies:
    min    - 12.12ms
    max    - 90.91ms
    median - 39.39ms
  Requests:
    Total Requests - 244088
    Requests/Sec   - 16232.20

======= FastAPI + Uvicorn =======
$ ./rewrk -h http://127.0.0.1:5002 -c 256 -t 12 -d 15s
Benchmarking 256 connections @ http://127.0.0.1:5002 for 15 seconds
  Latencies:
    min    - 35.44ms
    max    - 95.92ms
    median - 30.24ms
  Requests:
    Total Requests - 68520
    Requests/Sec   - 4528.04
#

Think this shows why its so important that you dont trust or use any benchmark that uses wrk as a means to determine your framework of choice

native tide
#

Hello, I'm looking for a phytoneer or pythonistas that could give me free tutoring. Covid has changed the way we look at the world and therefore I am learning programming to make a career change. Your efforts will not go to waste and I'm highly motivated in learning and studying which will make it easier for you to teach me.

The benefits you will get is learning how to teach and tutor with a highly willing, understanding, and adaptable student. If you're one of those rare people that values knowledge and wisdom then you shall receive it in abundance from me in return for your knowledge.

Please contact me trough PM.

flint birch
#

Hello, can anyone help me with adding a custom domain to a heroku app which is powered by Django ?

#

I tried to set up the DNS target to the domain ( the domain still points to the DNS that Heroku provides but somehow it failed to connect to my website.

quick cargo
flint birch
#

I have the student account with one hobby dyno available . I use that hobby dyno for my app but you know it still fails

hazy night
#

Hey can anyone help me with a quick quote on a website im building for a friend?

vestal hound
#

Hello, I'm looking for a phytoneer or pythonistas that could give me free tutoring. Covid has changed the way we look at the world and therefore I am learning programming to make a career change. Your efforts will not go to waste and I'm highly motivated in learning and studying which will make it easier for you to teach me.

The benefits you will get is learning how to teach and tutor with a highly willing, understanding, and adaptable student. If you're one of those rare people that values knowledge and wisdom then you shall receive it in abundance from me in return for your knowledge.

Please contact me trough PM.
@Go132#2500 IMHO

#

that would be the least I’d expect

#

it’s very unlikely that anyone really good would teach you for free

hazy night
#

well there's people who wouldnt mind being a side mentor for quick questions on issues either

vestal hound
#

well there's people who wouldnt mind being a side mentor for quick questions on issues either
@hazy night yeah, that’s the point of this server

#

but dedicated regular teaching...?

#

Hey can anyone help me with a quick quote on a website im building for a friend?
@hazy night what do you mean quote

#

I tried to set up the DNS target to the domain ( the domain still points to the DNS that Heroku provides but somehow it failed to connect to my website.
@flint birch are you using a paid plan?

hazy night
vestal hound
#

im building a site for a friends restaurant and i was originally going to do it for free but insists on pay and I dont know what I should ask for
@hazy night hm

#

on what basis would you like that assessed

#

simple way is come up with an hourly rate and record how long you took to build it

true scroll
#

Oh my God I hate JavaScript

#

Thank God for Python

#

but I cannot believe this language

#

function multiplyTwoNumbers(a, b) {
  var product = 1;
  for (var i = 0; i < arguments.length; i++) {
    product *= arguments[i];
  }
  return product
} 

>>> multiplyTwoNumbers(3, 2, 2) 
>>> 12
#

WHY IS THIS ALLOWED?

dapper tusk
#

Because it's convenient in some cases.

true scroll
#
var a = z; 
a = add_one(a); 

function add_one(x) {
  return x + 1;
}

var z = 4;
#

Why allow me to name and specify the quantity of parameters

#

and then just treat it like a suggestion

#

also why is this not any sort of NameError, why does JS not do NameErrors at all

#

and why are all the data types named such obtuse things

#

I'm sorry for the rant, I'm sure I'm missing something with JS

dapper tusk
#

The language follows different rules than python

true scroll
#

but right now it's completely impenetrable to me, and I'm not really a completely junior programmer

#

and Python is not my only language

dapper tusk
#

It mostly focuses and not crashing and in cases where most languages would crash it tries to create some sensible result

true scroll
#

I would prefer a crash

dapper tusk
#

Try typescript instead, it doesn't make that horrible mistake

#

Yeah, it's not a very good paradigm

true scroll
#

but then it's just compiling to JS

#

I don't like all these dependencies

#

on what is the language you're forced to use if you want code that runs client side on a browser

dapper tusk
#

Modern JS is quite nice though

true scroll
#

I believe I'm using modern JS

dapper tusk
#

var is not modern JS

true scroll
#

I was messing around with a Node interpreter, let me check my version

dapper tusk
#

Functions are still weird though

true scroll
#

yeah I understand that now, let and const are much preferred

#

I didn't run into any of the issues with var that I've been told about but I'll take everybody's word on it and just not

#

The abstract equality operator

#

good God

#

WHY

#

I am doing this so that I can get a job because realistically web dev is the most accesible if you don't have a degree

dapper tusk
#

So that ==1 works on html and form contents

true scroll
#

but I shudder to think of the absolute horrors that exist in JS codebases out there

dapper tusk
#

Like, there are reasons for this nonsense. Just not very good ones

true scroll
#

I can't believe people learn JS as a first language, I would never recommend that

vestal hound
# true scroll I would prefer a crash

JS was conceptualised as a scripting language that would be used by beginners who just wanted to add some functionality to their websites and might not have formal education

#

accordingly, it tries to kind of work in most cases

dapper tusk
#

It's not that bad, and you get to do graphical things other than turtle really soon

true scroll
#

A crash would help a lot more

#

it makes bugs a lot less difficult to fix

dapper tusk
#

True

vestal hound
true scroll
#

Python is great for new devs in this regard because there is just a right way to do things

vestal hound
#

shrug it's where we are now and it's too late to change many things

true scroll
#

and the amount of absolute insanity you can do in Python is not very much

vestal hound
#

not sure about that one

true scroll
#

because the language just puts it's foot down and says "no"

#

Relative to other languages

vestal hound
#

hm.

true scroll
#

Compared to Java, C, C++ especially, etc

#

It's pretty good

vestal hound
#

I would say that Python is relatively high on the scale of "you can do dumb things"

true scroll
#

really only Golang is comparable in enforcing sanity

vestal hound
#

lower than C/C++, higher than Java

dapper tusk
#

Rust's entire idiom is sanity

vestal hound
#

because of dynamic typing

true scroll
#

Python manages that insanity fairly well when you have a good understanding of the language though

dapper tusk
#

So does JS

true scroll
#

when they say "everything is an object" they really mean it

#

and when you stop thinking of things that would be a primitive data type in other languages as a primitive data type

#

it makes a lot more sense

vestal hound
#

and dynamic typing is always a source of many errors

dapper tusk
#

Python is not really unique in anything.

#

Though decorators are probably a python feature first

true scroll
#

It's not completely unique nor is it perfect

#

but it's easily my favorite mainstream programming language

#

and it is very mainstream

vestal hound
#

me too

#

there are a lot of things I wish I could change though

true scroll
#

C++ is horrible as well, JS reminds me of that in some ways

#

there are too many "right ways" to do things, though for very different reasons

vestal hound
#

"there should be one and only one obvious way to do it" died a long time ago

true scroll
#

C++ just has such a disgustingly bloated standard library that you could be using it for a year and read somebody else's program with no external dependencies and have no real idea what is going on

dapper tusk
#

Consider padding strings in python

true scroll
#

I agree, some things need to be trimmed

#

there shouldnt' be so many ways to format strings

#

most functional things can probably go honestly

vestal hound
#

I would prefer to keep the functional parts

true scroll
#

lambda and map is usually redundant

#

right, but comprehensions and generators usually got you covered

#

and are nicer to read when it's not your code

#

filter is situationally useful though I would say

vestal hound
#

you don't see this much in Python, but the main point of map is composability, I guess

#

like

processor = flow(
    map(f),
    filter(g),
    flat_map(h)
)

processed_data = processor(raw_data)
#

but yeah, I would agree

#

Python's map/filter are a bit weird

#

I probably use reduce the most

true scroll
#

I forgot about reduce

#

😭

#

What do I do about this JS problem though, what should I do for a Python web dev stack?

true scroll
#

I'm sort of on the Flask train right now, I hear Django's learning curve is kind of steep

#

and I don't really like being locked into one kind of DB

#

I want to learn a very flexible stack

#

that can be scaled up and down as needed for different projects

#

and just get very, very competent using that stack

#

typescript is looking to be a must though I think, I'll have to be comitted to an asylum if I have to work with JS without it

vestal hound
#

well

#

I mean

#

IMO SQL works fine

#

for most cases?

true scroll
#

Yeah but it would totally be overkill for some

vestal hound
#

I would also reco something like FastAPI

#

over Flask

vestal hound
#

like it seems to me the cost of creating an SQL database is not really that high any more

true scroll
#

No real sensitive or permanent user data being stored server-side, JSON is perfectly fine for that

#

Like I want to build out a web app that's a synced Pomodoro timer that just basically has rooms that you get a custom link for

#

and the only real database needs would be storing some random session specific user ids, some config settings for the session, and various information about the timer or whatever

true scroll
#

relatively impermanent data

#

that wouldn't be a major loss if it were lost

vestal hound
#

no I mean like

#

where would you store the JSON?

true scroll
#

server-side

vestal hound
#

so

true scroll
#

it wouldn't be client downloading JSON or whatever

vestal hound
#

in a file?

true scroll
#

sure, I see your point

#

there is a relationship there

vestal hound
#

shrug like my PoV is that there's not much cost to creating a database any more

true scroll
#

I haven't done a lot of work with relational databases

vestal hound
#

be it SQL or something like MongoDB

#

etc.

#

also, your host might not allow file uploads

#

or

#

on-instance storage might be ephemeral

true scroll
#

most likely would be deployed to a VPS

#

but yeah, that would be correct for something like Heroku

novel socket
#

So many smart people here 🤯

true scroll
#

Not really lol

#

I'm sure he knows a lot more than I do

#

I'm really just getting started with web dev

#

I probably think I know a lot more than I actually do

vestal hound
#

these are just my semi-educated guesses

#

but yeah

#

Django is rather huge

#

and chonky

#

and a bit outdated.

#

I have heard good things about FastAPI

true scroll
#

I think I'll probably stick with Flask

vestal hound
#

and it doesn't come with a database layer

#

so that is nice

true scroll
#

I like it quite a bit so far

vestal hound
#

for my next project

true scroll
#

Python already has some database support in the STL

vestal hound
#

I really want to use an async native framework

true scroll
#

so that is always an option

vestal hound
#

C++ background?

true scroll
#

Somewhat

vestal hound
#

true scroll
#

It's not my favorite language, mostly C

#

that was my first language actually

vestal hound
#

C is a beautiful language actually

true scroll
#

I love C

vestal hound
#

apart from the macros

#

🥴

#

okay sorry but anyway back on topic

true scroll
#

Yes, C + Python is a thing of beauty though

vestal hound
#

I honestly don't like some of Flask's design decisions

#

global requests are icky

true scroll
#

Such as?

vestal hound
#

and, IMO, like Django, it's kind of showing its age

true scroll
#

I don't follow

#

global requests meaning what?

vestal hound
#

like you know how

#

the request object

#

isn't passed as an argument to routes

wicked elbow
#

anyone know why im getting this error? UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte pulling from a ForeignKey field. its just a string to the filepath so i dont get it

vestal hound
true scroll
#

is it passed implicitly?

wicked elbow
#

being passed back from the API to my frontend. db is set up correctly because i can follow it in my db viewer

true scroll
#

the routes object I mean, or as part of some "magic" that FLask is doing for you?

wicked elbow
#

its django

vestal hound
#

that always refers to the current request being handled (because Flask is sync)

#

which is just a 🥴 model to me

vestal hound
#

where in your code

#

going to assume somewhere in the parser or serialiser layers

true scroll
#

I still need to learn how to into async

#

actually I can go do that right now, off to MDN

wicked elbow
#
class PostsSerializer(serializers.ModelSerializer):
    upload_src = serializers.SlugRelatedField(
        many=False,
        read_only=True,
        slug_field="src"
    )

    class Meta:
        model = Posts
        fields = ["id", "uid", "datetime", "gid", "src", "upload_src", "description", "type", "likes", "comments"]
#

has to do with the SlugRelatedField im pretty sure

#

src is the key in both models

true scroll
#

I also need to learn how to actually read and write SQL lol, embarrasing to say but I've been using ORMs as a crutch

vestal hound
#

async is the future of web IMO

#

like right now I'm already running into very real problems

#

because DRF doesn't support async

wicked elbow
true scroll
#

?

true scroll
#

why do you have a PORT in your URL

vestal hound
#

what's the relevance

wicked elbow
#

the entire site is async.

vestal hound
true scroll
#

is the url just forwarding to an IP instead of you setting up CNAME stuff properly?

vestal hound
wicked elbow
#

its text. its the filepath

#

its running on a dev server

true scroll
#

😱

wicked elbow
#

static links arent up yet

true scroll
#

This has a bad security smell to me

#

I don't know exactly why because I don't have the requisite knowledge

wicked elbow
#

still in developement. its up in dev so my testers can pass the errors to me

true scroll
#

but I think sharing your debug enabled dev server is not a good idea

vestal hound
true scroll
#

and sending passwords and username over http is a very big no no

#

that much I do know

wicked elbow
#

eh, its not gonna change anything, because the entire thing is gonna change once its in production.

vestal hound
#

which opens up possible attack vectors

wicked elbow
#

yes, but theres no information to steal anyways. anything youll get from the dev page you can find in the js anyways. its not masked

true scroll
#

You should still probably be emailing yourself debug messages if you're not just testing o localhost though

real hare
#

Hey guys, in Flask I'm wanting to receive the request value of an input field. am i fetching it by doing?

request.data.<input_fieldname> ?

#

Flask is the backend for my app

wicked elbow
#

probably true, but eh. really doesnt change much

real hare
vestal hound
#

anyways

#

my guess is that there's an encoding mismatch

#

like expecting UTF-8 and getting ASCII

real hare
#

Using this:


python -m smtpd -c DebuggingServer -n localhost:1025

true scroll
#

I would consider wiping EXIF data on upload

#

There's only one image that doesn't come from Facebook up there right now, but it looks like EXIF data isn't sanitized from the toher ones

vestal hound
#

it's actually something I need to look into for my current project

#

I know it'll be a problem on launch but I haven't gotten around to it

true scroll
#

pretty simple actually

vestal hound
#

no the actual removal is simple

#

but

#

okay so basically what I need to do is

#

on upload

#

verify that it's actually an image

#

strip metadata

#

create several versions

#

and push to storage

#

(oh, and this is where I would REALLY appreciate async)

true scroll
#

Why the several version?

vestal hound
#

different sizes

tidal saddle
#

Could you just save the largest size/resolution and resize on demand? Or is storage less of an issue than doing that?

true scroll
#

That would be my first thought, offload image resizing to the client

vestal hound
#

never done this before

#

and sometimes it kind of feels like premature optimisation...?

#

but the thing is

#

it's defo meant to be mobile-friendly

#

and

#

assuming each image is 400 kb or so?

#

there are cases where

#

as many as 7-8 images need to be loaded at once

true scroll
#

Is there a maximum image upload limit?

vestal hound
#

and my gut feel is that downloading a few MB of images to display a page for mobile is a bad idea

vestal hound
#

there will be, but I haven't implemented that yet

true scroll
#

What exactly are you building? '