#web-development

2 messages ยท Page 212 of 1

plush anvil
#

im trying to automate this report, but i cant change the value of 1. Door lock 'Disabled before any troubleshooting'. How do i get it right? Ive tried sending keys but they dont change the 'current value'

graceful igloo
#

Hi all. I built a flask app that gives me dog images via an API it requests pictures from.

Im wondering how to make a panel and a button for a page. I imagine being able to give users the ability to click the button and getting a new image in the panel until they decide to quit.

#

Whatโ€™s the best way to go about this?

wind abyss
#

How can you process an image and then upload it to a Django ImageField within the model?

inland oak
wind abyss
#

At least for me, there is an attribute error whenever I try to process an image file

inland oak
#

so the procedure would be...

#

Store image in Image Field

#

get its path

#

run processing commands on it

#

Optionally, saving to DB only at this point the path

#

The biggest trouble I see with images in general...

#

that only their path is stored in db

#

while it should be ideally stored the image itself ๐Ÿ˜‰

wind abyss
#

I see

#

Do you mind if you could take a look at my code?

inland oak
#

fixing it, you need to do something like....

#

converting image to base64

#

and storing base64 in db

#

usually MongoDB is recommended for file/image storaging though

#

not sure how well SQL database will work with it

#

it depends on, can it store images with floating size? should be good without contraint in theory, it needs to be checked

wind abyss
#
class TiffModel(models.Model):
    name = models.CharField(max_length=450)
    image = models.ImageField(blank = True, null = True)
    processed_image = models.ImageField(blank = True, null = True)

    def save(self):
        img = Image.open(self.image)
        output = BytesIO()

        images = []
        tensors = []
        processedArrays = []

        tiffStack = []
        ###=============== Conversion ================###
        # Read tif, convert each page into arrays in images[]
        for i in range(img.n_frames):
            img.seek(i)
            images.append(np.asarray(img))

        # Read every numpy array, convert to tensorflow, process by dividing by 2
        for x in images:
            tensorX = tf.convert_to_tensor(x)
            processedTensor = tf.math.divide(tensorX,2)
            tensors.append(processedTensor)

        # Convert back to numpy array
        for x in tensors:
            processedArrays.append(x.numpy())

        # Convert to tif
        for x in processedArrays:
            tiffStack.append(Image.fromarray(x))

        img = tiffStack[0].save(self.name + ".tiff", compression="tiff_deflate", save_all=True, append_images=tiffStack[1:])

        # Save tiff file into model data
        img.save(output, format = 'TIFF', quality=100)
        output.seek(0)

        self.processed_image = InMemoryUploadedFile(output, 'ImageField', "%s.tiff" %self.img.name.split('.')[0], 'image/tiff', sys.getsizeof(output), None)

        super(TiffModel, self).self() 
#

I think the processing part worked well enough, but the actual saving to model throws an error everytime

#

Would you say the base64 approach would be effective to solve this issue?

inland oak
#

according to a bit of googling

#

base64 approach is not advised

#

they recommend continue storing just file paths

#

due to higher speed efficiency

#

But, that's not final answer, because NoSQL databases potentially can be good

#

some people who dealt with them should be asked

inland oak
#

there are some cases when it could be cool to store it completely in dbs, but highly likely it is not yours

wind abyss
#

I see I see

#

Unfortunately whenever I use the save method my django dies

lusty wigeon
#

I want to achieve this.. Which will be optimal way to do multiple forms? Also multiple files, email sending (have done already not difficult for me outside django, but does not have an idea to achieve in django in my context), pdf template for downloading report.. I am Django Beginner.. Kindly share some resources (short videos, or blogs) , ideas to do it easily (expert opionion), github repos (each part perfectly explained separately or combined).. Thanks alot in advance..

inland oak
#

you should look into getting a hang of one of big three frontend frameworks: React / Angular / Vue.js

#

backend framework will add just login feature + ability to send by email

#

most of the heavy coding would be needed in frontend

#

I could recommend this book to get started in frontend basics ๐Ÿ˜‰

#

And this one for javascript

#

After those two, getting started in Vue.js or React should be not a problem

#

depending on how you value your data safety about user logins and scaling, backend could be potentially a lot of work to do too, but that would be technically non essential for minimum viable product ;b

lusty wigeon
#

Ohh I see I though it is totally backend work.. I have done some work already but not satisfied with my results so asking here... I know html css, a bit.. But you shocked me that it is heavy frontend task.. But how can I manage multiple forms in context of django? by the way thanks for answering..

inland oak
inland oak
#

where you need you can apply just a regular Javascript / JQuery, but you know... it will be a pain in the ass ๐Ÿ˜‰

#

you will have far less capabilities to implement nice visual interactive interface
frontend framework will give freedom to implement all desired features at maximum

lusty wigeon
#

login is easy and done already in django.. the only issue was multiple forms and files.. which is I think easy in JS.. let me search for it on web...

#

Thanks you guided me well.. Thanks..

inland oak
#

fine for minimum viable product, but a food for thoughts to think for scaling/data safety situations if necessary

lusty wigeon
inland oak
#

just page one: your first form

#

sending result to verification into backend and send back as sticky cookie

#

rendering form 2

#

inputting email and sending back to django

#

reading the cookie with data from form 1

#

doing stuff, sending answer

#

the only a bit I am unsure, how multiple files attaching works ๐Ÿ˜‰ never needed it

#

bare bones functilnality but still a functionality

lusty wigeon
inland oak
#

yes, nice introduction to javascript
and have a shame to be not distributing pirate copies here

verbal pagoda
#

@inland oak do they make some book like a brain friendly guide head first brainf or head first asm?
i want to learn asm....

lusty wigeon
verbal pagoda
#

yes

inland oak
verbal pagoda
#

hmm... it means asm is not brain friendly lol ok

inland oak
#

some of them became a bit outdated

wind abyss
#

Could someone help me with my code?

inland oak
wind abyss
odd belfry
#

Ignore if already solved.

wind abyss
crystal siren
#

Hi all,
I should do following task by python as a rehearsal:
"Create a load-balanced (public) REST API serving some json from an existing (loaded)
database and make it trivially easy to deploy on either AWS"

I don't know what does "load-balanced (public) REST API" mean!!? I would appreciate it if anyone could help me for understand it.

inland oak
#

so Load Blaancer would be having its own Public IP

#

user requests your backend at loadbalancer public IP

#

and he is redirected semi-randomly to one of your replicated APIs

#

thus distributing workload on machines horizontaly

#

the task can be fulfilled in actually at least three ways

#
  1. Most simple way:
    manually installing REST API at every server
    and raising load balancer as another VPS that has HAPROXY installed with config pointing to your REST APIs
    (Or optionally manually clicking cloud provider GUI to have cloud providers Load Balancer)
#
  1. Smarter way:
    You use at Least Docker to install applications
#
  1. Even smarter way:
    You use Ansible to auto install REST API and Haproxy load balancer as code from your development machine
#
  1. Even smarter way further:
    You scratch the haproxy VPS and instead
    you write terraform code (or Pulumi or similar tool used), that raises cloud provider load balancer pointed to your VPSes with REST APIs
#
  1. Even smarter way beyond further:
    You don't deploy your code on your own, CI tool like Gitlab CI tool does it for you, you just press a button to confirm production deployment if necessary, or no buttons is pressed, just code git commited to repository ๐Ÿ˜‰
#
  1. Ultimate way:
    Your terraform code creates Kubernetes Cluster
    REST API is auto loaded to docker registry by Gitlab CI
    Gitlab CI applies manifests to auto install everything into cluster
    Kubernetes auto creates providers cloud balancer
crystal siren
#

Thank you very much for your absolute explanation. ๐Ÿ™‚ I'm familiar with terraform, ansible, docker, ... and totally designing CICD but in this case I don't know how should I create REST API by python

inland oak
crystal siren
#

No I know k8s as well

inland oak
#

well, then use Ultimate way. ๐Ÿ˜‰

#

All you need making dockerized python web application that gives at least hello world

#

10 code lines to do that + docker file

crystal siren
#

and dose it contain "... serving some json from an existing (loaded)
database" ?

inland oak
#

REST API is not assuming database usage

#

although wait

#

perhaps assumes ๐Ÿค”

#

or not

#

no, no. mistook it with CRUDe applications.

inland oak
# crystal siren and dose it contain "... serving some json from an existing (loaded) database" ?

https://www.redhat.com/en/topics/api/what-is-a-rest-api#:~:text=A REST API (also%20known,by%20computer%20scientist%20Roy%20Fielding.
It looks like REST API assumes just having stateless JSON formatted application
So you should be good without database

crystal siren
#

Thank you so much for your help, ๐Ÿ™‚ so I should start

inland oak
inland oak
#

and not with dev server

crystal siren
#

for sure thanks

strange nacelle
#

I'm using django, how do I specify the path from where to get the templates? It takes by default from Personal Account\templates\ and I need from Main\templates\ Help pleas

lusty wigeon
#

Hi.. I want some html table editable with styles.. Which can communicate easily data with django... How? resources needed...

crisp cove
#

Hello everyone I'm new here! Name's Mike๐Ÿ„โ€โ™‚๏ธ

serene prawn
inland oak
#

creating / reading / updating / deleting those objects

#

it is a bit hard to imagine how can be CRUD without some stateful objects lifecycle to change

serene prawn
#

Yeah, but you don't have to store them yourself, your CRUD api could be a gateway to some microservice

inland oak
#

๐Ÿค” more proxies to the god of proxies.

serene prawn
#

Yep

cerulean badge
#

(django) is there any built in non negative validator for duration field?

rough rover
#

For python web developers, didn't you need to understand networking?

#

For People who did what did you learn.

crisp cove
#

good day everyone, please I want to know why this isn't displaying what's on my view. This is django by the way

lavish prismBOT
cerulean badge
crisp cove
#

Thanks I've figured it out

cerulean badge
strange nacelle
#

Rather, you forgot to add a link to the urls.

ember adder
#

Django project: I have a CBV to display information about a Volunteer object. In that view, I'd like to display a list of objects (VolunteeringJob) related to the Volunteer object. Each line in that related objects list will have a delete button. So I was wondering what's the best way to handle this?

My initial idea was to have a seperate view for VolunteeringJob and my information view would call its get to have the list, then call its delete to delete an entry and so on. Is there a better way/different way to do it?

strange charm
#

can someone help me with react + django?

#

i'm making a job portal

#

want to do stripe intigration

unique shore
#

React is a frontend framework

strange charm
#

i know that

unique shore
#

And stripe is something you would do on the backend

strange charm
#

yes

unique shore
strange charm
#

i tried this

#

already

unique shore
#

Oh lmao

strange charm
#

i need some other logic

unique shore
#

you can search something up on google

strange charm
#

yes

unique shore
#

like โ€œstripe integration with Djangoโ€

#

I canโ€™t really help as I have never used stripe and have minimal react experience

#

But I do have some Django experience

strange charm
#

Can i ping DM?

unique shore
#

Sure

strange charm
#

Can you ping me? i'm not able to ping you

unique shore
#

Try now

ivory lotus
#

in python, I have the following code:
views.py

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('wall/', include('art.urls')),
    path('admin/', admin.site.urls),
]

and when I go onto there, it returns a PageNotFound. All the code is in wall/, but how would I redirect the user to wall/ once they enter my development server? pithink

marsh canyon
#

you can use django's redirect view for / the home page to redirect to /wall/

#

here is the documentation

#

lemme know if you face any problems regarding the redirect

#

this is be all you need
path('/', RedirectView.as_view(url='/wall'), name='go-to-wall'),

#

you can also give the pattern name instead of url

whole garnet
#

which is better flask or django?

ivory lotus
ivory lotus
#

ok

#

is the bot responding

#

thanks btw

manic frost
#

!warn @regal root Stop spamming. This is not a platform for hiring or job seeking.

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied warning to @regal root.

native tide
#

Hey! Has anyone done Angela yu web development course??

steel solstice
#

Hey, can someone help me find a themeforest HTML template for the following. I am trying to find a site that allows students to submit online projects under different categories. This is in case something similar to the science fair gets cancelled, there will be a backup way for judges to view and judge the projects. Basicly, I want something as close to that. If you are able to help please dm me with the link of the site you found. Thank you!

ocean slate
#

Hello can someone help me in my flask project

#

i have a admin dashboard
in which students can post their complaints on the panel and on the home page of the panel all the complaints which student has posted will be shown there
and here i have two student for example
the main problem is .. when I post a complaint from first student account, then all the complaints are visible on the second student's home page also
i want complaints on home page of the user who is currently logged in
this is the problem

#

In simple terms - A student can see only their posts(or complaints) on their admin panel rather than seeing every student's posts

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied mute to @tribal tusk until <t:1642439046:f> (9 minutes and 59 seconds) (reason: mentions rule: sent 16 mentions in 10s).

prime carbon
#

!ban 927832768078020608 Only here to disrupt voice channel and spam ping.

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied ban to @tribal tusk permanently.

glad sigil
feral night
#

Hi, does anyone know flask and flask-sqlalchemy?

#

I have problem with proejct structure and database relations

native tide
feral night
#

also where should I include this db = SQLAlchemy(app) into app or models file?

native tide
#

I'm a bit rusty on flask web dev, but I'd say you'd put that into app file, if you're not thinking yet about directory structure

feral night
native tide
#

hmm. as a general rule, I think you want to avoid wildcard ('*') imports

feral night
#

ok, so just classes with tabels I guess

native tide
#

try to follow the documentation. that'd be my recommendation

inland oak
#
import modules as modules

is is in general safer import indeed

#

modules.stuff to use

native tide
#

as far as I understand pep8 gives no preference to:

import mypkg.sibling
from mypkg import sibling
#

but which is better?

inland oak
#

what makes less mess in your imports ;b
while remaining precise what u use

#

prefering precise imports, using mass import as package to avoid too many imports

#

although import as package has advantage

#

over precise import

native tide
#

(np)

inland oak
#

because anywhere in your code, it is seen from which package the function is

#

so... I guess package import is good as general method

feral night
#

If someone has any good flask-sqlalchemy repo with modules, cofig and database relations repo I would liek to see

native tide
#

Darkwind, tnx

native tide
#

this may be outdated somewhat

#

but in general look to miguel for guidance

#

not certain, but I think he's also the author of the flask sqlalchemy extension

#

(altough, I may have read some critiques about it from sqlalchemy devs sometime ago)

#

@feral night ignore the link above

feral night
#

oh ok haha

native tide
#

sorry

#

my mistake

#

don't

feral night
#

I just need a good guide how to connacthe files like: app.py, modules.py, this for sure: config.yml and routes,py

native tide
#

but it links to the post above

#

I just thought the post above was outdated, because it's dated to 2017

#

but it seem it's up to date

#

also from the first link thats dated to 2017:
there's metadata on the site like:

$ python3
Python 3.9.6 (default, Jul 10 2021, 16:13:29)
#

so it's been updated for sure

inland oak
#

I was complete zero, and was given to implement everything from the guide within 5 days

feral night
#

so should I follow this tutorial or do Yo urecommend something diffrent?

inland oak
#

this is good tutorial ๐Ÿ˜‰

feral night
#

ok thanks

inland oak
#

I was hired because of it

native tide
#

I'm not sure there's anything better for flask to be honest :)

#

(for a beginner)

native tide
#

someone should mention to Miguel to update the date on the tutorial post

feral night
#

Do I need to import db here in routes.py?

from flask import jsonify, request


@app.route("/")
def hello_world():
    
    message = {
        'message':'Connected!'
    }

    resp = jsonify(message)
    
    return resp




@app.route('/api/add-data', methods=['GET', 'POST'])
def submit():
    if request.method == 'POST':
        if request.is_json:
            data = request.get_json()
            new_label = label(label_name=data['label_name'])
            new_question = questions(question=data['question'])
            new_answers = answers(answers=data['answers'])
            
            db.session.add_all([new_label,new_question,new_answers])
            
            db.session.commit()
            return {"message": f"Data has been sent successfully."}
        else:
            return {"error": "The request payload is not in JSON format"}

# Get All Data
@app.route('/api/get-data', methods=['GET'])
def get_all():
    if request.method == 'GET':
        all_labels = label.query.all() 
        all_questions = questions.query.all()
        all_answers = answers.query.all()
        
        
      
        
        return jsonify(all_labels+all_answers+all_questions)```
#

and tables?

carmine cipher
#

Hello guys !! Please can someone tell me what best language for backend ?

slate narwhal
#

@native tide @verbal pagoda Thanks guys

unique shore
carmine cipher
unique shore
#

C# and the .net platform is growing in popularity and will definitely be useful In the future

#

Itโ€™s also really fun to work with

carmine cipher
unique shore
#

those are great options

carmine cipher
unique shore
#

yeah great

#

good luck

topaz widget
indigo kettle
#

what are we lol-ing

#

just that django is python?

#

I guess it is a strange requirement to have 1 year of python and 2 of django

topaz widget
indigo kettle
#

yeah I see what you mean

#

I will say that it is very different to be scripting with python and writing a website with django

topaz widget
#

True. But if you have 2 years of experience with Django, doing scripting with Python should be no problem.

native tide
#

Finding someone that has done 2 years of Django without having done python scripting first in some capacity is like finding a unicorn. If you did find someone with only 2 years of writing Django code, I bet they would struggle to script things in Python.

#

It's much more likely that they started with Python scripting and then picked up Django so pretty hard to test the theory

indigo kettle
#

yeah I wonder. It seems like people try to jump into web development with django without having much programming experience beforehand though

#

at least from things I've seen in this channel

#

I feel like I've seen quite a few people just diving in the deep end

native tide
#

Django's ORM in particular is barely python

#

It's a language itself

indigo kettle
#

for sure

#

I feel like being good at django isn't about knowing python, it's about knowing all the class based views you can inherit from, how to write better sql queries through the orm, popular 3rd party django plugins like DRF and django-filter...

native tide
#

I've done a lot of Django the past couple of years, but still get to write regular python too which is nice.

ember adder
ember adder
native tide
ember adder
#

Learning and doing Django really taught me a lot of the Python basics: inheritance, list comprehension, using packages, testing, etc. I mean, at some point in a project you'll have to extend Django code using Python basics and advanced stuff. In my case it was very formative and I learned a ton on the side (reading two scoops, TDD, CI/CD, Docker, Ansible, Terraform, Git, GitLab products, Django-cookiecutter, SAST, databases, reading and understanding documentation, payment integration, etc.)

ember adder
native tide
#

thanks for sharing, giant.

feral night
#

How can I get all data witch relations?

@app.route('/api/get-data', methods=['GET'])
def get_all():
    if request.method == 'GET':
        all_labels = Label.query() 
        all_questions = Questions.query()
        all_answers = Answers.query()
        
        
        result1 = labels_schema.dump(all_labels)
        result2 = questions_schema.dump(all_questions)
        result3 = answers_schema.dump(all_answers)

        
        return jsonify(result1+result2+result3)
topaz widget
native tide
#

i do not understand

feral night
#
from app import db,ma



class Label(db.Model):
    """Data model for Labels."""

    __tablename__ = 'Label'
    label_id = db.Column(
        db.Integer,
        primary_key=True,
        
        
    )
    label_name = db.Column(
        db.String(64)
        
    )
    

# Label Schema
class LabelSchema(ma.Schema):
    class Meta:
        fields=('label_id','label_name')

# Init Schema
label_schema = LabelSchema()
labels_schema = LabelSchema(many=True)


class Questions(db.Model):
    """Data model for Questions."""

    __tablename__ = 'Questions'
    question_id = db.Column(
        db.Integer,
        primary_key=True,
        autoincrement=True
    )
    question = db.Column(
        db.String(64),
        index=False,
        unique=True,
        nullable=False
    )
    label_id = db.Column(
        db.Integer,
        db.ForeignKey('Label.label_id')
    )

    label = db.relationship('Label',lazy='select', backref=db.backref('Question', lazy='joined'))
    

# Question Schema
class QuestionSchema(ma.Schema):
    class Meta:
        fields=('question_id','question')

# Init Schema
question_schema = QuestionSchema()
questions_schema = QuestionSchema(many=True)


class Answers(db.Model):
    """Data model for Answers."""

    __tablename__ = 'Answers'
    answer_id = db.Column(
        db.Integer,
        primary_key=True,
        autoincrement=True
    )
    answers = db.Column(
        db.String(64),
        index=False,
        unique=True,
        nullable=False
    )
    question_id = db.Column(
        db.Integer,
        db.ForeignKey('Questions.question_id')
    )

    question = db.relationship('Questions',lazy='select', backref=db.backref('Answers', lazy='joined'))


# Answers Schema
class AnswersSchema(ma.Schema):
    class Meta:
        fields=('answers_id', 'answers')


# Init Schema
answer_schema = AnswersSchema()
answers_schema = AnswersSchema(many=True)
#

Look at PK and FK

#

I want to query everyting with relations

#

like

#

Label_name, question, answers

#

connected by relations

#

I'm in the middle of finding a solution

@app.route('/api/get-data', methods=['GET'])
def get_all():
    if request.method == 'GET':
        # all_labels = Label.query.join(Label.label_name.filter(Questions.question)) 
        #all_questions = Questions.query.filter(Questions.label_id).join(Label.label_id==Questions.label_id).all()
        # all_answers = Answers.query.all()
        
        all_questions = db.session.query(Questions,Label).select_from(Questions).join(Label).all()
        
        # result1 = labels_schema.dump(all_labels)
        result2 = questions_schema.dump(all_questions)
        # result3 = answers_schema.dump(all_answers)

        
        return jsonify(result2)```
#

still that's not it

#

any ideas please?

#

@native tide

native tide
#

hey dude

#

btw

#

dont use just `

#

use ```py

#

for formatting

feral night
#

oh ok, thanks

native tide
#

what is "db"

feral night
native tide
#

ah

#

wym pk and fk

inland oak
#

A year and few months ago my mad marathon began.
Worked at least 8 hours and more in working days
Plus often spending evenings and weekends time to self studies.
Anything I learned I applied at work and had a lot of practice to solidify every skill

#

My start was exactly after finishing university

strange charm
#

Can someone help?

#

i have installed the package as well

wooden ruin
#

did you make sure to add django_cors_headers to your installed apps and middleware too?

strange charm
#
    'django.middleware.security.SecurityMiddleware',
    "corsheaders.middleware.CorsMiddleware",
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]```
#
Requirement already satisfied: django-cors-headers in ./env/lib/python3.6/site-packages (3.10.1)
Requirement already satisfied: Django>=2.2 in ./env/lib/python3.6/site-packages (from django-cors-headers) (3.2.10)
Requirement already satisfied: pytz in ./env/lib/python3.6/site-packages (from Django>=2.2->django-cors-headers) (2021.3)
Requirement already satisfied: sqlparse>=0.2.2 in ./env/lib/python3.6/site-packages (from Django>=2.2->django-cors-headers) (0.4.2)
Requirement already satisfied: asgiref<4,>=3.3.2 in ./env/lib/python3.6/site-packages (from Django>=2.2->django-cors-headers) (3.4.1)
Requirement already satisfied: typing-extensions in ./env/lib/python3.6/site-packages (from asgiref<4,>=3.3.2->Django>=2.2->django-cors-headers) (4.0.1)```
#

Can you please check?

glacial portal
#

How do I write tests for websites?

native tide
#

Can someone please explain what does the scope attribute do i have a hard time understanding it. Thanks!

wooden ruin
swift wren
#

hey guys, what would websockets be used for in a CRUD application

swift wren
inland oak
sacred cipher
#

hey guys does anyone know how i can transfer AWS route 53 registered domain to cloudflare

#

because when i try to point the nameservers towards cloudflare, it never detects it

#

thanks ๐Ÿ˜„

swift wren
#

are these libraries compatible?

    - djangorestframework
    - django-cors-headers
    - celery
    - django-redis
    - django-celery-beat
    - django-celery-results
    - django-graphql-jwt
``` no matter if I don't know their functionality
midnight musk
#

Hi Guys

#

I am Bash

#

i made a project using computer visoin and AI

#

This is the link, can you guys reiview it and give me suggestions ?

inland oak
#

there only possible trouble I can see in

  • djangorestframework
  • django-cors-headers
  • django-graphql-jwt
#

they all deal with modifying a bit requests (if to look just at names from afar), so in theory there can be some sort of trouble, so better to check ๐Ÿ˜‰

swift wren
#

ah okay

#

hey mate

#

can you help me make a descion

#

is graphql better than rest?

#

apparently they can work side by side

#

but in a application that uses both, what kind of application would that be

inland oak
#

apply REST for simple stuff
apply graphql when you have complex input/output requests

swift wren
#

oohh

inland oak
#

i did not deal with graphql, but that's my presumption.

swift wren
#

thats very helpful

#

i dont think i would have many complex data commuinications

#

im gonna add in some statistics later on the application, but i wont have large quantity of data

inland oak
#

as far as I know graphql allows to make better granularity to requests.
in one request you can query data with multiple relationship between.... lets say model objects
and to receive output matching those requests in one go

#

so it could be efficient for stuff like quering data of Social Network profile type

swift wren
#

like make it faster when querying more tables

#

at a time

inland oak
#

I guess. We can get all data in one request instead of multiple ones

#

the proffit in faster request time there is indeed

#

that's just my assumption about how graphql works, I stil did not deal with it ๐Ÿ˜‰

#

i was more spending time to learn how to do better infrastructure and faster development

#

still having a lot to learn

swift wren
#

lol, better infrastructure in Django xD

#

btw do you have any idea about redis/kafka/pubsec ?

#

a person told me i need a cache

inland oak
swift wren
#

oh wow, im also using celery

inland oak
#

I am interested to learn kafka next. It would make a nice architecture

swift wren
#

wait is redis even the same thing as kafka?

#

what is kafka do you know?

inland oak
#

as far as I know Kafka implements Event Streaming pattern, where we can send send events into it and attaching multiple backend listeners to the events
the difference is that perhaps it is possible to have multiple subscribers to one published event, probably

#

and that kafka stores those events in some different way probably

#

and just in general listeners are attached in a bit different way to distribute workload

#

.... basically my knowledge about kafka ends at 5 years old knowledge

#

wait a second

inland oak
#

xD kafka for 5 years old.

swift wren
#

aye yo

#

this looks amazing

#

how made this the heck

cerulean badge
#

I need to implement 2 timers for both chess players, this could be done with just setInterval and decrement the timer every second but it isn't accurate and tend to drift so we could instead calculate the timedelta from a datetime to the future called <white/black>EndDatetime and subtract current time from it, for pausing, we can add the timedelta of the amount of time the opponent spent on their move to <white/black>EndDatetime. and instead of doing all of this, I could use timer.js lib instead. now my question is, is it too trivial problem to use a lib? i think one could just use it and save their time.

serene prawn
unique shore
twilit needle
#

There's a lot of things you have to consider when comparing graphql with REST.

#

Graphql offers a lot of benefits over rest, it exposes a typed and unified interface for your clients. You fetch exactly what you need with graphql. Which generally means you need to make lesser network requests with graphql

unique shore
#

ye but the hype around gql was kinda overblown

#

its definitely really good ,but i dont think it will be replacing rest soon

twilit needle
#

But practically, I would recommend REST over GraphQL for anything you use in production, if you want to build with python.

GraphQL was released in 2015 which means it's a relatively new piece of technology. Fewer people use graphql- so you have fewer guides and resources to learn from.

What are best practices? What should I do with x in graphql? How do I validate input data?

There's no right answer to this yet, and wont be for the foreseeable future. You have to figure out what works for you on your own.

unique shore
#

mhmm

twilit needle
#

The python graphql ecosystem is also not completely production ready, when compared to the nodejs ecosystem, though we have nice libraries like strawberry and graphene.

#

So IMO graphql in production is a deal with the devil

#

I spent a lot of months learning this.. lol?๐Ÿ˜…

#

What's qloom?

#

I couldn't find any related resources, sorry

#

Could u link some

#

And also I dont think this is the right place for adverts

violet mesa
#

If I have an api that fetches some data from another API for some features but otherwise does everything by itself (interacting with presentation and data layer), is it still a technically a gateway api?
eg my zoo api fetches images from dog, cat api before returning it to zoo.com

radiant garden
#

probably not

#

most web services use some sort of other service, for example a database

violet mesa
#

Yeah, i need to write a report so I was wondering if gateway is correct usage here, thanks for the clearup

cyan ivy
#

hm what's graphQL?

dense slate
#

An API query language.

twilit needle
#

It's going to take years for it to replace rest

unique shore
#

like sql

#

they are both query langs but not the same thing

dense slate
cyan ivy
#

Hmm

serene prawn
#

Why not use both? ๐Ÿค” I heard some companies use graphql for querying data and rest for mutations

dense slate
#

What's the point of using two?

grizzled coral
#

Hello

#

Who uses selenium?

serene prawn
grizzled coral
#

Hello

#

import platform

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chromium.options import ChromiumOptions
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.utils import ChromeType

Selenium setup...

if platform.system() == 'Linux':
opts = ChromiumOptions()
service = Service(ChromeDriverManager(chrome_type=ChromeType.CHROMIUM).install())
else:
opts = Options()
service = Service(ChromeDriverManager().install())

opts.headless = True
opts.add_argument('--disable-dev-shm-usage')
opts.add_argument('--no-sandbox')
opts.add_argument('--disable-gpu')
opts.add_argument('--remote-debugging-port=9230')
prefs = {"profile.default_content_settings.popups": 0,"download.default_directory": r"C:/Users/apskaita3/Desktop/Nasdaq_file/companies/","directory_upgrade": True} # IMPORTANT - ENDING SLASH V IMPORTANT
opts.add_experimental_option('prefs', prefs)

driver = webdriver.Chrome('C:/Users/apskaita3/Documents/New folder/chromedriver.exe',options=opts, service=service)
#driver.get(url='https://google.com')
driver.get('http://www.nasdaqomxnordic.com/aktier/microsite?Instrument=VSE95425&name=Amber Grid&ISIN=LT0000128696')
driver.find_element_by_id('exportIntradayTradesCSV').click()

time.sleep(5)
driver.close()

#

not works

golden bone
#

My guess is the problem is with your crud but you haven't shown the code for that

grizzled coral
golden bone
# grizzled coral Nothing session created

It's such a pain to get Selenium working in most environments, especially if you're not doing it headless. There is a Docker image, that's the most reliable solution I've found

dusk portal
#

how can i make a dm chat feature in django

#

i guess i

#

will need django channels

#

websockets

opaque rivet
#

yep

wheat verge
#

can django projects be deployed in netlify

grizzled coral
golden bone
# grizzled coral Docker can get download files automatically?

Docker is just a tool for building containers, you could try running that Python code inside a container with headless Selenium if you can't get it working otherwise. I personally find that easier then fighting with Selenium, but if you've never used Docker before either I don't know which path will be easier for you

golden bone
wheat verge
wheat verge
warped aurora
#

using datatables and trying to get my length button and filer in the same row, not sure how to manipulate the dom structure

slate narwhal
#

I'm trying to make a navigation bar using HTML and CSS, does anyone have any ideas on why text-align: center; isn't working for me?

radiant garden
#

Is there any modern async web thingie that supports streaming uploads? I am using Tornado and I thought there'd been progress with Starlette etc, but checking it out it seems they hold the whole file in memory as well

#

I don't know what's hot and popping these days, I thought this would be a good place to ask

#

I basically want to receive a file over an API endpoint and put it on S3

serene prawn
#

last_build_date = Column(DateTime, default=datetime.now()) your default is incorrect, you shouldn't call now here pithink
You can use Enum(native_enum=False) here, it would store your enum as a string

atomic dome
#

Hey, I am a bit confused about how to proceed. Should I learn vanilla Django before going into REST framework?

native tide
serene prawn
#

e.g. datetime.now without parenthesis ()

slim cape
#

HI I just want to know where I would go to learn python

#

I know absolutely nothing and am trying to decipher old code

cobalt hatch
#

you can go to w3schools

#

or youtube

#

free courses

scenic furnace
#

Is there a better way to do password input than just making an HTML form and password type input?

#

It's slightly concerning that this method just dumps the password into URL parameters and queries the URL specified in the form's action parameter.

native tide
scenic furnace
#

HTTP for now, I don't own an SSL certificate

#

Also I am not setting any info up for real, only test info.

native tide
# scenic furnace HTTP for now, I don't own an SSL certificate

HTTP if running locally in dev or even on a server without any important information is fine. POST should move it to the request body instead of the URL. Then, when you're ready and need to secure it, check out LetsEncrypt for a free SSL cert for HTTPS.

scenic furnace
#

awesome

scenic furnace
#

ok, so here's what I have on the HTML side:

<form method="post">
    <label for="username">Username:</label><br>
    <input type="text" id="username" name="username"><br>
    <label for="password">Password:</label><br>
    <input type="password" id="password" name="password">

    <input type="submit" value="Log in">
</form>
#

My route for this page:

@app.route('/login', methods=['GET', 'POST'])
def loginPage():
    print('serving login page')
    if request.method == 'POST':
        print('login request with form data {}'.format(request.data))
        return render_template('login.html')
    else:
        return render_template('login.html')
#

For some reason, the request.data is empty, why?

#

oh doi ๐Ÿ˜† flask leaves that empty if other mimetypes succeed...

slate narwhal
#

Anyone know what I'm doing wrong here? align-items: center; isn't working for me

lavish prismBOT
#

Hey @brave compass!

It looks like you tried to attach file type(s) that we do not allow (.html). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.

Feel free to ask in #community-meta if you think this is a mistake.

brave compass
# slate narwhal

I got this working while reviewing this Stack Overflow link: https://stackoverflow.com/questions/5995405/how-to-center-a-navigation-bar-with-css-or-html#

.navbar {
  width: 100%;
  height: 45px;
  align-items: baseline;
  align-content: center;
  margin: 0 auto;
  text-align: center;
}            

ul {
  display: inline-block;
  ...
}
slate narwhal
lavish prismBOT
#

Hey @brave compass!

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

brave compass
#

Sorry, I need to run off to bed, but will check in the morning if it's still a problem and see what else I can think of.

static zealot
#

I want to send a link in email which is going to trigger a get method. It is working perfectly in postman like that. But how can I include those headers to my link?

#

But it gives me this error:

{ "statusCode": 401, "message": "Access denied due to missing subscription key. Make sure to include subscription key when making requests to an API." }
indigo kettle
#

how are you sending the request, with the requests library?

static zealot
#

I am trying to send this request with a browser, the api is running on server.

wide anchor
#

Iโ€™m a self taught developer, and I feel like Iโ€™m missing something huge.

Iโ€™ve been through some Udemy tutorials, built real world projects for my business, and worked with JavaScript and python for about a year now, but I feel as if Iโ€™m still missing something from my education of front end development. It still seems complicated to me and like I just donโ€™t โ€œget itโ€.

Process goes like this:
Have problem thatโ€™s needs to be solved, or idea โ€”> find a similar tutorialโ€”> make a extremely rough plan in my head โ€”> build something with a roll of duct tape and stack overflow โ€”> repeat

I almost feel like I can program but donโ€™t understand computer science.

What books, guides, or articles can I read that talks more about theory and larger topics, beyond just a tutorial of โ€œhow to use x frameworkโ€? How can I start to see the big picture?

native tide
#

@wide anchor Find a problem you want to solve, then determine if what you already know is sufficient to accomplish it.

#

Realworld problems are the best problems to solve.

stark tartan
indigo kettle
stark tartan
stiff totem
#

In django + postgresql how can i get today's, tomorrow's and then next 7 days records respectively i mean, group them and get with annotation or something

native tide
#

"my business" << This is good as there is no one to fire you, you are free to try new things and implement them as you see fit @wide anchor

#

I envy ya ๐Ÿ™‚

indigo kettle
stark tartan
indigo kettle
#

just keep looking things up and reading

wide anchor
native tide
#

So what do you want to accomplish first? What's a 30 second elevator pitch on the thing that needs solving @wide anchor ?

stark tartan
wide anchor
native tide
#

An archive of videos can be telnet.

#

Why do you need principles, go quick easy fast, unless you want flash.

#

Do you want a problem to solve because you're bored, or a problem to fix because you need a solution.

wide anchor
#

Like:

How many requests to the db is too much?

Do I store the data in a local store (vue js) or do I fetch the data each time?

Other things like this

native tide
#

Depends on your DB and the popularity

#

Local, perhaps.

stark tartan
native tide
#

Again, you sound as if perhaps youre searching for an unsolved problem.

#

sqlite3 or postgresql

wide anchor
native tide
#

You don't need django if flask works just fine, or perhaps python3 -m http.server even.

#

I love to code too; it's a great hobby of mine.

#

But I don't search for problems, i search for ways to solve problems using python and semi-maybe-mostly niche things.

#

i.e.

wide anchor
#

I donโ€™t think there even needs to be a server component - just vue js and the database is my thoughts

wooden ruin
#

but if you have the time it's definitely worth going under the hood and getting all the tiny details about a particular subject,

wooden ruin
native tide
#

^

#

Let me ask you a question there biz owner.

#

Do you use Excel at work?

wide anchor
#

So Iโ€™m fetching about 1800 records in a firestore db each time the user loads up the site - and then the user will navigate using the sidebar to each video component - I was thinking it would be silly to refetch a video from the db if Inalready did

wide anchor
native tide
#

Ok.

#

CSV or XLS(X)?

wide anchor
wide anchor
native tide
#

yuck.

#

But ok, xls.

#

Is it formatted all pretty?

#

i.e. Do we need formulas?

wide anchor
native tide
#

The google sheets

#

do you have formulas in them pointing to cells within the sheet.

#

i.e. Can we export as a csv and do this better, and without uncle G looking over your shoulder.

#

If youre doing hourly Excel work, you're doing it wrong....

#

Excel is an output format only; executives and above.

#

So many companies, they do it wrong; painfully so. Oh the horrors......... =/

wide anchor
#

What would this look like at a high level example ?

native tide
#

What kinda db; something on aws maybe?

wide anchor
#

Fire base

inland oak
# wide anchor Iโ€™m a self taught developer, and I feel like Iโ€™m missing something huge. Iโ€™ve ...

oh, you are wishing how to plan the process of developing programming product. planning the project in a... more industrial way.
System Analysis & Design comes to rescue
it teaches how to select projects, how to set requirements what needs to be done, how to design its use cases / scenarios from user view point, how to design data flow diagramms out of it, how to plan database model objects and how to design implementations of them, how to plan UI, how to plan efficient code structure by modules/packages for implementation and finally processing to implementation stage.

wide anchor
inland oak
# wide anchor Amazing, so this will teach me the DESIGNING aspect of programming right ? But I...

mm yes, it teaches you how to design projects
But essentially it just give you sight how to do in a bigger picture
In order to design well technical parts you need to have a broad and deep understanding of core technologies
in order to design UI, you need to learn how to use tools like Figma for designing and all the reading how to plan interface in human friendly way
in order to implement / planning how to code well, you need to cover at least basic topics like:
Head First Design Patterns
Clean Code by Martin
unit testing principles practices and patterns (by Vladimir Khorikov), TDD
domain driven design by Eric Evans
and e.t.c.

#

Writing clean efficient code structure obviously requires learning different programming aspects how to do that
and all related good practices to it. Unit testing makes it the most amazing btw ๐Ÿ˜‰
Well and obviously coding well requires a lot of practice. Books are just a knowledge that needs to be practiced in order being useful.

#

The System Design book just gives you plan how to that in a scope of industrial project. It does not make you an expect in every specialized field to do it in the best way

wide anchor
#

Ok this is awesome - thank you, so by reading these books I could use the principles taught in them to write better, more efficient code for web development ?

inland oak
wide anchor
inland oak
wide anchor
inland oak
#

System Design and Design Patterns are sure memorably useful reading out of all of them

#

but it was just one among many.

#

I would stress again that learning Testing gives the best proffit in writing better code in a short time

#

in combination with a bit of DevOps tools like Ci/CD pipeline, Docker and e.t.c. it gives me the fastest development speed

#

without losing quality

wide anchor
inland oak
# wide anchor Good to know, Iโ€™ve always dreaded testing and ignored it hahah

I would be lying actually that saying just a bit of DevOps tools are necessary.
Actually all of them are needed to reach full happiness. to have Infrastructure as a code.

My process of development reached a stage where
Once I submit code to repository
It is auto build into docker container by CI/CD pipeline
runs unit tests
redeployed fully automatically with whole infrastructure (servers and e.t.c.) into staging environment
it runs integration tests that all microservice applications part work together in unison
and then saved as ready for deployment in one click to production

winged pendant
#

Hi everyone, has anyone had a problem trying to connect MySQL in django 4.0 using macbook pro with M1 chip?

inland oak
primal quartz
#

Hello, I would like to start developing a website but dont where to start. Is Django better or Flask?

#

and if so any tutorial suggestions?

inland oak
#

planning stuff in microservices makes it planned for bigger scalability
and just having easier / smaller code in independent parts. Makes stuff sort of... quite easy, simpler.

#

it brings its own set of problems though

#

But higher level infrastructure tools resolve them

wide anchor
inland oak
inland oak
#

and just going faster due to having everything out of the box

primal quartz
#

thank you for your help

inland oak
#

highly recommend this tutorial.

#

it was recently updated to flask 2.0

primal quartz
#

Great!

#

ill get started right away!

#

This is a huge help you guys thank you so much

burnt cedar
#

hello I was thinking of getting into web app development but Idk what roadmap should I choose

#

I will prefer if its related to python libraries like django or flask

#

should I just go with full stack course python oriented?

inland oak
# burnt cedar hello I was thinking of getting into web app development but Idk what roadmap sh...

btw for roadmaps: https://roadmap.sh/
considering that you ask about it in python Discord server, you are going to receive the most biased answer:
I think starting from python backend is the best option in terms of getting fastest development with being introduced to core programming concepts better
frontend is just not giving the same best practices efficiently IMO.
and switching from backend to front should be easier that from front to backend.
and I am biased to frontend ๐Ÿ˜‰ even if i cared to learn/practice it

burnt cedar
#

because I am looking for all in one thing

#

which teaches pwa , frontend , backend (with python)

inland oak
#

frontend in frontend frameworks, backend in python?

#

it is impossible to learn everything in one thing.

burnt cedar
inland oak
burnt cedar
#

oh

inland oak
#

for Frontend I would recommend React / Angular or Vue.js
Vue.js should be easiest out of them
To get started in frontend learn HTML/CSS first, this book is amazing

#

Then progress into learning Javascript

burnt cedar
#

thanks

inland oak
# burnt cedar thanks

mind you, that you are just learning frameworks and nothing out of programming concepts in those materials

burnt cedar
#

mhm

inland oak
#

bad code would be for sure ๐Ÿ˜‰ u need to learn more than that if you wish to be good

burnt cedar
#

๐Ÿ‘

wooden ruin
inland oak
#

Vue Cli 5 was setting me up everything from zero to fullest capabilities, including how the f*** to do testing, and offering in CLI interface all tools for all categories with bolierplated code.

#

I did not really learn how to do the same in Vite

#

I guess i missed that if it can do the same too

wooden ruin
#

Yeah i think you're right about vue cli having alot of good boilerplate code with everything you need to ready to go, setting up things like vuex or vue router is a real pain with plain vite. thinking of going back to vue cli 5 even if it means slightly slower build speeds.

strange charm
#

can i save form data before entering into the database. Means i want to save the form data and i want to create a entry only if the payment is successful.

#

django + react

strange charm
#

yes

#

stripe api

#

but how can i save form data. I can save the api data from stripe directly.

rotund perch
#

Heroku/Django
I Had an SQLITE configurations on the settings.py, why is this not working? Ive also changed the ENGINE to postgres in the config vars

This is my django settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
strange charm
#

So, suppose i have a job model. How can i call this job model? after the payment is successful? means i understand that i can use the data and store directly into my database. But what about the data which i need from the frontend form? How can i call that data after the payment?
because customer data will be provided by stripe
so its easy to save directly.
so for example: I have name, age and address. I want to save this data from the frontend after the payment went through.
maybe wrong example.
suppose i have job title, salary, fulltime, location data. How can i save this data? this data is different from stripe api data.

tribal tapir
#

Hello im trying to upload from my front end to my back end server with flask

#

and i have an issue

#

that when i pass the file i dont get the file to my back end i get an empty ImmutableMultiDict([])

thick sinew
#

If I update Jinja without updating django will it create problems?

inland oak
vital harness
#

Someone know what should I use for parsing a database from a website? Iโ€™m working with python

inland oak
cyan skiff
#

hey guys. Im new to this field. Can I create a Python website with a personal account where the user can find only the information that I allow?

vital harness
# inland oak that sounds weird. Could u rephrase what you are doing

Sure. So, I have a school project and I need to look through prospects of different types of drugs to search some keywords in order to find an interaction between drugs. And Iโ€™m working in python and my professor told me that in order to do that I could use a method called parsing. I donโ€™t really know what that means so I was thinking that someone can explain or give an example or so.

inland oak
#

how your source of data looks like

vital harness
#

He told me that I need to extract data from a database in which I can find all this prospects. Iโ€™m still looking for that database because I have to do it for my country specific and it is quite difficult to find here.

inland oak
#

was it given to you

vital harness
#

Nope. And I donโ€™t know yet how the database looks like because I couldnt find it yet. I was hoping that I can least find what parsing is

inland oak
# vital harness Nope. And I donโ€™t know yet how the database looks like because I couldnt find it...

parsing can be done in different ways, since you don't know how your database looks like, it is impossible to say which method of parsing you need
I would assume that you will probably find database in the form of csv documents with data separated by ,

highly likely all you will need to upload database, just reading lines and applying split function by delimiter ๐Ÿ˜‰ it depends on how it is structurized

#

technically there is so called web parsing, but i think highly likely, you don't need it

vital harness
#

Ok, I understood. Appreciate your help

polar gull
#

Hiii. I am currently building a notes taking website with django, pretty basic one. I added the note creation and deletion functionality succesfully and also added the login authentication functionality. But there is one thing i am struggling with. I want to show a user only his notes not every else note that exists in the database. Any idea how that might be done. How should i design a model or write a view for that. Would really appreciate the help.

dense slate
#

usually your function is like def notes(request):

#

the request holds that user information

cerulean badge
#

I am using 2 datetimes to the future called deadlines, and use it to calculate the times remaining for the timers for both players in chess. I get that deadline in isoformat from server after every move is played. my question is how accurate are 2 devices time when they are set to automatic date and time?

dense slate
grizzled coral
#

selenium.common.exceptions.WebDriverException: Message: unknown error: DevToolsActivePort file doesn't exist

cerulean badge
#

so there will not be any latency issues

dense slate
#

Ah, no idea, might be a good question for game dev.

grizzled quartz
#

also have cname record for api

native tide
#

Would I be able to ask a question about relative paths here? (html+java noob)

dense slate
lucid vine
#

How come my new site is loaded perfectly fine inside postman, but in browsers I get ERR_CONNECTION_CLOSED

#

DNS is set up...

#

wait, do .dev sites require HTTPS? ...

dense slate
#

Or wait, I mean working in dev, meaning locally, doesn't.

#

You getting any kind of more specific error than that?

#

Is that when you're fetching data?

native tide
#

I asked in a help channel, but it ended up going dormant!

#

this assignment is purposely meant to have unorganized files, with the intention of us using ..\ to get the img src to work! I was able to fix the navigation id from character page.html to go to index.html using ../../index.html

#

But I cant figure out the img pathing

inland oak
native tide
#

I'm sorry, this is my first week of the course (and im learning remotely for the week due to being sick)

#

can you explain that a bit?

#

do you specifically mean the backslash?

inland oak
# native tide can you explain that a bit?

as far as I know browser paths can be possible only in two formats
Absolute and Relatives

absolute - /src/blabla.jpg
relative - blablabla.jpg
relative - ../blablabla.jpg

#

it is not possible to have \ file paths for web site

native tide
#

oh that path isn't to a website! It's a relative path leading to a local image file

inland oak
#

unless perhaps windows filesystem allows it for local file paths? ๐Ÿค”

native tide
#

yea!

inland oak
#

HTML usually means web site ๐Ÿ˜‰

native tide
#

file-paths-incorrect\main-images\header-images\neit_logo.png would be the full relative path

#

but it doesnt work since character pages.html isnt in a shared folder so we need to use ..\ to get it to work

#

(we arent allowed to move files manually, since the sake of the assignment is the pathing)

inland oak
#

as far as i understand u a using plain HTML without frameworks, right?

#

just open console in the folder of your HTML file that has links to images

native tide
#

uh correct, for example

<main> <header> <img src="..\..\..\main-images\header-images\neit_logo.png" alt="NEIT Logo"> </header> <hr> <nav> <a href="../../index.html">HOME</a> | <a href="characters page.html">CHARACTERS</a> </nav> <hr> <section> <h2>Monsters</h2> <img src="images\monsters\alien.jpg" alt="Alien"> <img src="images\monsters\godzilla.jpg" alt="Godzilla"> <h2>People</h2> <img src="images\people\macho man.png" alt="Macho Man Randy Savage"> <img src="images\people\mrt.webp" alt="Mr T"> <!--Image with absolute path--> <img src="https://vignette.wikia.nocookie.net/monstersincmovies/images/0/09/Sulley_002.jpg/revision/latest/scale-to-width-down/340?cb=20130512141939" alt="Sulley"> </section> <hr> <footer> <img src="..\..\..\neit-tiger.png" alt="NEIT Tiger Mascot"> </footer> </main>

inland oak
#

and find a path by hand from current HTML template to images

#

or by console

#

cd ..

#

dir

#

commands movements ๐Ÿ˜‰

inland oak
#

well, or just using absolute paths, which would be easier. but since assigment is not allowing it, lets do it relative ๐Ÿ˜‰

native tide
#

yea we have to do relative, and we can't move files/folders. I have to have the neit_logo.png img src to display in the character page.html file by changing it's directory path using ..\

Is that what you're trying to explain?

inland oak
#

assuming trying to find path from this html to png

#

../../file-paths-incorrect/main-images/header-images/neit_logo.png

#

it will be basicallly something like this

#

.. - means going to parent folder

#

we moved twice to parent folder

#

and then moved to subfolders of going to png

native tide
#

yea for example I did ../../index.html for a navigation link to go to index.html from character page.html

inland oak
native tide
#

not allowed

inland oak
#

it just looks so gross with space. not sure why

native tide
#

it's a pre-coded assignment

#

we're only changing the paths for images

inland oak
#

okay, %20 I think will work instead of space

#

browser can escape spaces

native tide
#

oh my gosh I fixed it. I see what you were trying to explain.

Original relative path: file-paths-incorrect\main-images\header-images\neit_logo.png

fixed: ../../main-images/header-images/neit_logo.png

#

I was doing this the whole time:

#

..\..\main-images\header-images\neit_logo.png

#

I didn't realize I that I was allowed the change the backslash to a forward one... ๐Ÿ˜ฐ

dense slate
#

I can't think of a situation I ever use a backslash in web dev.

#

And I've worked on both linux and windows machines.

lucid vine
#

as soon as I fixed https it started working

#

chrome & firefox enforce it

dense slate
#

Yea, I thought you meant working locally in a dev environment.

lucid vine
#

nah, .dev tld

#

which is really stupid if you ask me

dense slate
#

๐Ÿคท๐Ÿผโ€โ™‚๏ธ

lucid vine
#

like why does a .dev need ssl enforced??

#

especially when devs tinker with stuff

dense slate
#

That's surprising though, because I've been told https is only really necessary for websites using sensitive information.

lucid vine
#

why not enforce it on other tlds then

dense slate
#

That http isn't a problem otherwise.

lucid vine
#

well... yes and no

#

you should always use https these days

dense slate
#

should, sure.

lucid vine
#

unless you are developing some micro services

#

for internal use only

#

but then I recommend gRPC

#

everything should use ssl

#

I hope dns over https becomes more widespread too

dense slate
#

But .dev specifically enforces https?

#

I didn't know any of them enforced it

lucid vine
#

yeah, the dumbest thing ever

#

chrome won't open .dev in plain http

#

it refuses

#

lol

#

same with ff

#

I was like wtf why curl works but chrome errors out

#

just google things

dense slate
#

Oh I see, google bought it and now redirects traffic to https in chrome.

lucid vine
#

if I knew that I would never buy a .dev domain

#

live and learn I guess

dense slate
#

Is there a benefit to the .dev domain? Instead of dev.yourdomain.whatever?

lucid vine
#

there ain't any benefit to any tld over the other really, except name and SEO

#

but I wanted a .dev for my personal website

native tide
#

I was wondering do people Still prefer website which are made from html ,css,js considering the fact wordpress Exists?

lucid vine
#

lmao

lucid vine
#

I can count 10 reasons at the top of my head

#

first of all PHP

#

second of all WP

#

it's all shit

dense slate
#

You can't build an advanced custom web app in wordpress.

lucid vine
#

you can actually but it's hell

dense slate
#

Yea WP is really slow.

lucid vine
#

and WP uses that same tech (HTML,CSS,JS)

#

so it's basically just another framework

#

but for beginners

#

a "CMS"

native tide
#

Because nowadays people make website using wordpress( probably earn good amount too) then label them as web developer so I was just confused.

lucid vine
#

naaah, publishing a WP site ain't web dev

#

it's like writing a blog

#

lol

#

if you write custom wordpress plugins and such then you are a dev.

dense slate
#

Yea I've seen plenty of web dev job advertisements where they use wordpress. I suppose technically, sure you're developing a website, but you won't get any advanced apps coming out of that. At least I don't know of any.

lucid vine
#

At my last job we had a lot of WP sites that were very customized

#

I hated it all

#

but publishing content for WP ain't web dev.

#

they probably just use it so they put it in an ad

#

at the least you should be comfortable with PHP

snow edge
#

I have a few images in my html file with <img> tag. When I load the html in flask using render_template, everything else gets loaded instead of the images. Can anyone tell me how to fix this?
Please ping me when u reply

drifting radish
#

How do I have an idea to make a 3d lol game you want too much memory from the server?

dense slate
drifting radish
thin marten
thin marten
#

ah, #game-development might be a better place to ask about it? either way i don't know enough to help further than making sure people know what you are trying to ask

daring pollen
#

just getting started with django, I kinda get the basics and working on a site to display content, how would I go about (or what should I search for) daily querying a site to refresh data for the app?

#

going to look into django-cron but open to other suggestions

scenic furnace
#

I am making a Flask web app. What's the best way to update the contents of a page every second or so?

drifting radish
#

Can i create game in unreal engine and put this on web?

wraith dagger
golden bone
scenic furnace
#

ok

rare lagoon
wild thunder
#

hey guys!

I'm having a strange problem with flask sql alchemy, please check if you can help me, I'm stuck

How to create a many-to-many relationship with 3 tables using flask-sqlalchemy? the default docs only work for 2 tables, not 3.

Thank you!!!

#

the result of the table would be
id | table1_id | table2_id | table3_id

dense slate
#

Maybe the M2M could relate to a through model that has 3 FKs?

#

I'm not quite picturing the scenario. Can you describe how the models would interact?

scenic furnace
#

Ok so I'm using Flask's session plugin and need to test having multiple users logged in at once. For whatever reason, I can't use my phone for this because my college's network is set up funky and my phone can't see my laptop. Is there any way to isolate two Firefox instances to allow me to do this?

indigo kettle
#

start an incognito session

scenic furnace
#

good idea

#

thanks, it worked!

#

Does flask-socketio respect flask-sessions or do I need to do funky stuff for that?

lavish prismBOT
#

Hey @snow edge!

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

remote ridge
#

I have a basic Python desktop app I need to convert to web app since I can't get on mobile stores quickly enough due to an earlier than expected release because reasons. What's the quickest and dirtiest way to do that?

#

I think it's some variety of flask or django? Shove me in the right direction. Please. Not expecting miracles and it needn't look pretty.

silk dove
#

Hi, I'm using Django and I have this function on one of my models

def diferencia(self):
    dif = self.likes - self.dislikes
    return dif

and then using it on a template to show the rating of a post, but I wanna make a query which order the posts lists using this rules of likes-dislikes but I don't know how to do it

posts = Secret.objects.order_by('likes')[::-1]

and this is my query right now but I don't know how to make the query properly

uneven bloom
#

Guys can I deploy flask app on a local machine. It keeps crushing when I ran it in development mode for a longtime example after 2 days whereby it a method that runs in the background after every one minute.

indigo kettle
#

probably something like py qs = Secret.objects.all().annotate(diff=F('likes') - F('dislikes')).order_by('-diff')

inland oak
wild iron
#

I was trying to create a login system using django

#

but when i try to log in

#

literally nothing happens

#

i thought maybe what if it doesn't even receive the username and password, and that is what is happening according to me

#

coz i printed it

#

and i saw this

#

it returns None None

#

so can someone help me in figuring this out

inland oak
barren lava
#

hello

fringe magnet
#

Hi

#

I want to learn how to coding web with python, where can i start please?

inland oak
north mantle
#

lets say we have a json first time we cache it.. second time we gonna cache it it has changed, now how can we get only the new data. Mind that some been replaced, or been deleted

rotund perch
#

Hello,(Django rest framework) does anyone knows how to send custom errors to the frontend. I know (try-except) and if (except) return a Response, but does that returns that response if theres a 500 error when requested for the frontend?

north mantle
#
{"clips":[{"name":"18758979.mp4","time":"48 minutes ago"},{"name":"987654.mp4","time":"46 minutes ago"}]}
#

maybe i can just pull name, and somehow save a list of the latest one, if its not same then == new item

wild iron
#

Something like this i guess

rotund perch
inland oak
twilit needle
#

So.. I have a small question

#

It's related to naming actually

inland oak
# rotund perch but thats on django templates I think right?
from rest_framework.response import Response

@api_view(["GET", "POST"])
def get_ping(request):
    return Response({"message": "pong!"})

if u wish sending error, just change response to have appropriate http error status code

return Response({"error": "my custom error"}, status=400)

or if you wish even more clarity and following best practices

import rest_framework.status as status_codes

return Response({"error": "my custom error"}, status=status_codes.HTTP_400_BAD_REQUEST)
twilit needle
#

I've got my flask views like this:


app = Flask()

@app.route():
def create_todo():
    return _create_todo(...)

def _create_todo():
    # service function
    pass

Here I've got a naming clash between my services and routes. Is there a better way to name them?

#

Please ping me when help!

serene prawn
#

e.g.

class CreateTodoCommand:
    def __init__(self, session: Session):
        self._session = session
    
    def execute(model: CreateTodo):
        ...

@route
def create_todo(model: CreateTodo):
    command = CreateTodoCommand(get_session_somehow())
    command.execute(model)
#

For simple crud service would probably be better but i'd use command if you have some complex logic

native tide
#

Hello folks,
I currently have a flask app deployed on pythonanywhere and I want to add celery to the arsenal, but since pythonanywhere has no support for that, i need to migrate.
What are the service I could use that would provide a server for the workers and a redis broker ?

serene prawn
native tide
#

The thing is, I won't be migrating the flask app from pythonanywhere, I just need to distribute the tasks so I'll need a remote broker as well.

#

For the flask app to be able to send the tasks over to Redis

serene prawn
#

You still can host your services anywhere, but it think there are managed solutions too

native tide
ivory lotus
serene prawn
#

Didn't have any experience with managed redis and other services, so i can't recommend anything

native tide
#

Alright, thank you !

native tide
serene prawn
#

Well, it's not local if redis is on vds and your app is on pythonanywhere ๐Ÿค”

inland oak
#

and it will become local to your flask app (for easiest setup I would recommend putting flask to docker-compose too, so it would be right in the same docker network, which will make domain address to access redis, same as the service name in docker-compose)

twilit needle
#

Wondered if I could have plain service functions

native tide
#

Which is not what I want to do

serene prawn
plush bloom
#

hey anyone here?

golden bone
#

(don't ask to ask, just ask)

plush bloom
#

ok

#

i need help in registering my model onto the admin site in django

#

i think i did everything correctly

#

but the database is not popping in the admin site

#

@golden bone

golden bone
#

show your code

plush bloom
#

ye 1 sec

plush bloom
plush bloom
#

is there anything else u need?

#

@golden bone

golden bone
plush bloom
#

u asked to show the code...

#

and i thought u can help

#

srry

golden bone
#

I was encouraging you to ask your question... I don't know Django too well but it looks like your migration worked

plush bloom
#

yeaa

golden bone
#

I don't think models automatically show up in Django admin, you might need a Model admin class ?

#

admin.ModelAdmin

#

Yeah, check the docs,.I think that's what you're missing

plush bloom
#

ok thanks a lot man

barren lava
plush bloom
#

hello

barren lava
#

you solved your problem?

plush bloom
#

nope

#

can u tell wut is the problem using the photos of my code?

barren lava
#

yup,

#

no problem

plush bloom
#

r u really good with django?

barren lava
#

In order to see your user table on admin site , you need to register model

plush bloom
#

this is how u do it right

barren lava
plush bloom
#

yep did that only

barren lava
#

and you can check your admin site.

plush bloom
#

yes i did

#

but it was not there

#

if u r open to join a vc or something i can screen share

native tide
#

I just want to make auto making thread / creating list. I just checked in console, the error says

"{"error":"Unexpected token u in JSON at position 0","version":"1.3.0"}".

How can I resolve this error?

The Python Code:

#
import requests
from io import BytesIO

headers = {
    'authority': 'traderie.com',
    'method': 'POST',
    'path': '/api/adopt_me/listings/create',
    'scheme': 'https',
    'accept': '*/*',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'en-US,en;q=0.9',
    'authorization': 'Bearer ',
    'content-length': '722',
    'content-type': 'multipart/form-data; boundary=----WebKitFormBoundarypqN01X2kArSkOHBn',
    'cookie': '_ga=GA1.2.850822138.1642224893; _gid=GA1.2.556027755.1642224893; usprivacy=1---; ad_clicker=false; _pw_fingerprint=6818da724c1a866373d3104d2cd082e4; _gcl_au=1.1.628091182.1642224893; _hjid=cc106801-cff3-4156-afad-2b5845f96325; _hjSessionUser_2441420=eyJpZCI6IjQyMjdmMjVjLWEyMjItNTI1Ny04NjUwLWY3MmU1NjEyYjNlZiIsImNyZWF0ZWQiOjE2NDIyMjQ4OTMyMDAsImV4aXN0aW5nIjp0cnVlfQ==; _hjSession_2441420=eyJpZCI6ImVkODE1MDc5LTYwNWItNDIzMC1iODUxLWZkOGRlNmM2YjM3MCIsImNyZWF0ZWQiOjE2NDIyMjQ4OTM0MzEsImluU2FtcGxlIjpmYWxzZX0=; _hjAbsoluteSessionInProgress=0; _pw_audience_segments=["1","3","4","5","6","7","8","9","10"]; __stripe_mid=a848c4df-5112-4afd-8bdd-2235857cc00abc7ef9; __stripe_sid=e1c6337b-f03f-4b93-8441-eb1d118cee58001fb3; _pw_audience_categories=["games_hardcore"]; _pbjs_userid_consent_data=3524755945110770; pwUID=369796799639702; __gads=ID=dcb867edd8f2877b:T=1642224926:S=ALNI_MYArRYYa1oDgieG9f1YFUuJjVv-oQ; G_ENABLED_IDPS=google; G_AUTHUSER_H=2; _gat_UA-176465218-1=1; _gat_gtag_UA_176465218_1=1; cto_bundle=5p2Tj182VmVrbFhLNUFmS3lZNXllZnk2b1UzbkYwR0JhVUFUMSUyRnplYWd1QWh1VyUyQmlrJTJGYjlOTU1XdE1xb050NjhHJTJCajczQW1MeDNQSnRoRG9tM2UzeHN1blk5Z2pHYllDUlJLQUxVUHVDclp1JTJGT0N6cHluWjdjZzRGNVdRZFhqeUJiQmZSZlVORnI0dGlhdnV4MDQ2YnZFeVVnJTNEJTNE; playwirePageViews=16',
    'origin': 'https://traderie.com',
    'referer': 'https://traderie.com/adoptme/product/1276977709',
    'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'empty',
    'sec-fetch-mode': 'cors',
    'sec-fetch-site': 'same-origin',
    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'
}

body = '{"acceptListingPrice":false,"currencyGroupPrices":[],"diy":false,"endTime":"","free":false,"item":"1276977709","itemType":"pets","makeOffer":true,"needMaterials":false,"offerBells":false,"offerNmt":false,"offerWishlist":false,"offerWishlistId":"","selling":true,"standingListing":false,"stockListing":false,"touchTrading":false,"wishlist":"","amount":1,"properties":[{"id":1,"property":"Flying","option":true,"type":"bool","preferred":null},{"id":2,"property":"Rideable","option":true,"type":"bool","preferred":null},{"id":9,"property":"Age","option":"Full Grown","type":"string","preferred":null}]}'

resp = requests.post(f"https://traderie.com/api/adopt_me/listings/create", data=body, headers=headers)

print(resp.text)
wild iron
#

why am i getting this error, when even this error page clearly states that /register exists

wild iron
#

i think the problem is with the keyword register, i just tried signup instead of register and it worked

#

noo

#

thats weird

#

coz i tried private window

#

and this works

#

but the normal window is putting a / in the end for some reason

#

so need to figure out why its doing that

wild iron
#

fixed it by creating another app for register

carmine cipher
#

Hello guy . Please someone can share with me a good roadmap to learn efficiently mobile app.I really need it.

rotund perch
#
@api_view(['GET','POST','PUT','DELETE'])
def testView(request, id=0, get_type='all', title=''):
  if request.method == 'POST':
    return Response("THIS IS GOING TO POST(CREATE)")
  if request.method == 'PUT':
    return Response(f"THIS IS GOING TO PUT(UPDATE) THE ID {id}")
  if request.method == 'DELETE':
    return Response(f"THIS IS GOING TO DELETE THE ID {id}")
  if(get_type == 'all'):
    return Response(f"THIS IS GOING TO GET ALL BECAUSE THE GET TYPE IS {get_type}")
  if(get_type == 'one'):
    return Response(f"THIS IS GOING TO GET ONE BECAUSE THE GET TYPE IS {get_type} WITH THE ID {id}")
  if(get_type == 'group'):
    return Response(f"THIS IS GOING TO GET A  GROUP BECAUSE THE GET TYPE IS {get_type} WITH THE {title}")
  
  return Response("none of the functions worked..")

is this a good practice?

#

Ive just put a response for earch not the thing I want to do but just for showing the code and to be more clear

indigo kettle
#

I prefer the class based views for this kind of thing

#

think about if you should be using elif. Even if the functionality will be the same, the logic is easier to follow if you use elif

unkempt brook
short venture
serene prawn
short venture
rotund perch
#

Okay thanks!

short venture
serene prawn
lavish prismBOT
#

rest_framework/viewsets.py line 217

class GenericViewSet(ViewSetMixin, generics.GenericAPIView):```
short venture
serene prawn
short venture
serene prawn
#

It depends

short venture
#

Generic one also provides most of the necessary logic for CRUD operations, which is a big plus, since he won't repeat himself.

serene prawn
#

Well, having CRUD already written for you is obviously nice but often you need custom logic anyways

short venture
#

You can still override those logic in the relevant methods. Still much easier with Generic one.

serene prawn
#

Don't think so pithink Your requests might not map to your models 1:1

short venture
#

I don't think he's going to rewrite all the methods for the relevant HTTP verbs. That's not the case most of the time.

serene prawn
#

Simple example using a Post model: when creating it you might want to link it to the user, perform custom validation, etc.
Having that logic in a serializer doesn't seem to be right imo

short venture
#

Why? That's the perfect use case for the serializers. Since validations are purely meant to serializers. In normal Django, we use forms for custom data validation and in DRF, we use serializers.

#

Also, serializer's create method is also perfect use case for it. Linking the user.

serene prawn
#

If you need to perform a validation based on database state (e.g. user can't have more than 10 posts) would you put that into a serializer? ๐Ÿคจ

short venture
#

Where would you put that, and why?

serene prawn
#

Into APIView/ViewSet method or a service function/class

short venture
#

Because?

serene prawn
#

Because this way my business logic does not reside in serializers pithink

#

Also it's would be easier to test

short venture
#

Agree to disagree. ๐Ÿ™‚

serene prawn
#

Imo having multiple responsibilities in a serializer is not really a good thing

#

It should validate incoming data, that's all imo

short venture
serene prawn
#

Tbh forms and serializers are different things, though, they're similar

#

Also serializers are generally hard to work with compared to say pydantic models

short venture
#

You can see references of forms in that single article multiple times. To make it clear serializers are mostly the same of the forms.

serene prawn
#

Official does not mean i agree with it pithink

#

Why would single entity have multiple responsibilities?

#

It's generally bad

short venture
#

This conversation isn't going to some meaningful and senseful point. So no need to keep it.

serene prawn
#

I really don't understand why you should perform anything beyond validation in serializers

hexed crest
#

does anyone know what text editor i should use

unique shore
#

VSCode is the most popular code editor

scenic furnace
#

any text editor can be used, so just use one that works for you

#

I use vs code, or if I'm working command line-only I'll use vim, but I've seen people use notepad++ and several others with no issue

unique shore
#

Sublime too

serene prawn
#

I think PyCharm and VSCode are most popular atm

scenic furnace
#

Ok so I have Flask-Session and Flask-SocketIO running together. Currently, when I run emit() inside a @socketio.on function the client that sent the signal that triggered the function is the only once to receive it. How can I emit() to all clients as well as to only the one client attached to a session?

azure shard
#

Hello, I'm using Selenium to automate a purchase on a website. I'm not trying to automate captcha or anything, I just want to be able to input the captcha and then for it to move on.
Currently, I'm using ImplicitWait, but after completing the hCaptcha, it leaves me on the same page.

#

Any idea how I fix?

#

this is basically it

#

wait 40 seconds for captcha to finish, then continue however it doesn't allow that

#

it's just stuck on here

#

any help is appreciated :)

golden bone
lethal junco
#

please help, can't run open-edx on pycharm

#

any idea? I want to run it localhost

wide anchor
#

Hey guys, Iโ€™m looking for a 0 to 1, beginner to advanced JavaScript book that is written for people who already know how to code. Any senior devs in here have a good recommendations ?

lapis glade
#
async def image_get(image_uuid):
    if image_uuid != None:
      image_link = "https://media.valorant-api.com/weaponskinlevels/" + image_uuid + "/displayicon.png"
      return RedirectResponse(image_link)```

How instead of returning a redirect can i get the image and relay that without a redirect
lapis glade
inland oak
#

Not really to advanced advanced level, as it is impossible to fit it into one book

#

But the best covering beginning stuff

wide anchor
#

But Iโ€™m not great at the last 3

wide anchor
scenic furnace
#

Heads up for anyone testing multiple sessions in a Flask app and using Firefox to test: If you open multiple windows/tabs, they will share cookies and therefore share the session. Two Private windows are the same way. If you open a normal window and a private window, you can test up to two sessions at a time, but no more..

wet meadow
#

Could someone tell me some designs for my website?

azure shard
#

the issue is that after completing captcha, it just stays there

native tide
#

Multiple windows and tabs of the same browser will use the same session

quasi summit
#

Most probably wrong channel but has anyone written a Firefox add-on with Python or does know if it works and can point me to a tutorial or something?

#

Apparently it is not, need to do it in JavaScript

warm lagoon
#

if anyone has worked previously with selenium please take a look at my problem in #help_crossaint

wild iron
#

what could be causing this error in django

serene prawn
#

python is case-sensitive

wild iron
#

thankss

golden bone
drowsy rose
#

Hello Guys,
I'm currently working with a python project that needs to integrate a SOAP based WebService
and i need to upload images with MTOM.
I've been searching for libs that i can use to deploy, but i'm not finding anything.
Does someone knows or have any official/alternative method that works in this case?

strong wave
#

Hiya I am trying to run an python httpserver on localhost, what could cause this?

#

Im trying to run a python htttpserver on localhost. I created an index.html to show an opedata map. I can see the map, but some of its either white/gone, or it doesnt line up correectly. What can cause this?

tacit bridge
#

eee

native tide
#

Hi guys, i'm trying to pass an url as a parameter with django for a view function, but i cant' manage to do it and i haven't been able to find anything online

#

If i try to use any other string it works as intended, but it's for an url shortener, so i need to pass links

frank shoal
#

maybe use a query parmameter?

#

{{base_url}}/add?url=https://www.google.com

#

Don't forget to urlencode it

native tide
#

i'm gonna look that up