#web-development

2 messages ยท Page 198 of 1

limpid mason
#

I am hosting a private linux server which only has an IP. No domain name. Is it possible to implement a Cloufflare/Akamai like service on my server to protect it from DDoS and other attacks ? If yes, how acn I do it ?

fair sundial
#

obnoxious

manic crane
#

still struggling django.db.utils.ProgrammingError: column "date_of_birth" of relation "Occupier_occupier" does not exist

fair sundial
#

using axios or just a flask request?

#

and by values do you mean the data sent? if so

#
request.data
native tide
#

anyone here good with HTTP request and responses?

dusk portal
#

oh how can i build it

glacial yoke
#

Can someone help me please. I am trying to setup daphne with django in deployment. I already setup a supervisor config file, which launches both the gunicorn startup file and the daphne startup file. But for some reason, when I check the status of the supervisor, it says that gunicorn works fine, but daphne has a fatal status. Is there a way to check error logs? and what could possibly be the problem?

native tide
#

can i host my web site on rdp

#

??

serene prawn
#

@native tide rdp?

golden bone
native tide
#

??

golden bone
native tide
#

can u give me a video

#

pls

#

@golden bone

golden bone
# native tide can u give me a video

No, I'm not going to Google that for you but pick a platform and I'm sure there are multiple tutorials out there (Heroku and PythonAnywhere are probably both good enough on free tier)

native tide
#

no i have a vps not on a website

#

@golden bone

native tide
#

hello?

#

anyonr on

orchid olive
#

good evening
i move from w7 to w10, i reinstall python, flask, wtforms, etc but when i run flask it display an error like

error when uploading myproyect

any help on this error?

#

Error: while importing 'MyProyect', an error was raised.

orchid olive
#

FIXED! thanks for the help

native tide
#

hmmm do you also know django?

#

also what do you mean by back end?

#

what exactly does it comprise of?

lyric belfry
#

How can I make a button interact with a django model?

#

Basically I'm making a mini web clicker game and i'm using a HTML button it's storing the amount of coins to your account

#

So what's wanted is when I click for it to update the django model which stores the coins and then increment it by 1

serene prawn
dusk portal
#

@opaque rivet hey wassup bro

native tide
#

hey guys!

#

so the thing is, i dont know how foreign keys work

#
from django.db import models

class User(models.Model):
    username = models.CharField(max_length=50)
    #notes = models.ForeignKey(something)
    

class Note(models.Model):
    body = models.TextField(null=True, blank=True)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)


    def __str__(self):
        return self.body[0:50]
#

i want the user to have a notes object linked to it

#

by using foreign keys

#

the notes variable will contain the ids of all the notes the user has created, and i should be able to acess the notes body, updated, and created through the user.

dense slate
#

Notes.objects.filter(author="demi")

#

and it will point to the appropriate user object

#

so then you can do something like name_of_note.author.username

native tide
#

im getting an error while trying to create a foreign key

#
from django.db import models

class User(models.Model):
    username = models.CharField(max_length=50)



class Note(models.Model):
    body = models.TextField(null=True, blank=True)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)


    def __str__(self):
        return self.body[0:50]
#

heres the error :

#

django.db.utils.IntegrityError: NOT NULL constraint failed: new__api_note.author_id

limpid horizon
#

Anyone here knows how to make it so I dont have to relunch my dev site every time I want to update something in bottle?

#

I set Debug to true but it doesn't work.

dusk portal
#

idk why but im unable to add my custom template at reset password

#

at reset password i can load template , btw all things are working fine

#

but in reset password done , the mail what we get n complete idk why i cant load tempaltes

#

the name is also correct

#

im in trouble from last 2 days

#
app_name='users'

urlpatterns = [
    path('register/',views.register,name='register'),
    path('login/',auth_views.LoginView.as_view(template_name='users/login.html'),name='login'),
    path('profile/',views.profile,name='profile'),
    path('profile-create',views.profile_create,name='profile-update'),
    path('logout/',auth_views.LogoutView.as_view(template_name='users/logout.html'),name='logout'),
    path('password-reset/',auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'),name='password_reset'),
    path('password-reset/done/',auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'),name='password_reset_done'),
    path('password-reset-confirm/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'),name='password_reset_confirm'),
    path('password-reset-complete/',auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'),name='password_reset_complete'),

]```
#

app urls

#
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('index.urls')),
    path('account/',include('users.urls')),
    path('', include('django.contrib.auth.urls')),

]
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
``` main urls
#

btw in this tried changing the path also of django.contrib.auth.urls

edgy sable
#

I have a problem

naive crater
native tide
#

so is it not possible to make full stack websites with flask/django?

potent berry
#

Hi there, sorry to cut you off. I'm currently building a website for my concept art portfolio. I'm fairly new in website building and would like to ask if anyone has any recommendations for website hosting services? I'm looking into using Hostinger, though I've read some bad reviews about them. Thanks in advance! Sorry if this is a bit out of topic.

edgy sable
dusk portal
# edgy sable

Django
If yes after form tag u didn't wrote csrf token n if written so incorrect syntax

fossil pond
#

What's even strange is the fact that this code worked before

whole sierra
#

Can anyone tell me, is it safe having my homepage capable of showing private information once logged in? (in Django)

#

is this bad practice or unsafe?

dusk portal
#

what type of private info @whole sierra

#

password n all?

#

u can show email , name contact no. profile info n all , not password

whole sierra
#

@dusk portal yeah, behind the login is names, email and phone no.

assuming people wont be able to crack the username and password login. Will these be in anyway visible?

#

also, I am unable to associate @login_required with functions that dont return a request (render). is this safe to leave without @login_required?

native tide
#

so the thing is

#

the frontend is making a post request

#

and the backend is giving an internal server error

#
@api_view(["POST"])
def createAccount(request):
    data = request.data
    body = data["body"]
    print(body)
    return Response()
#

im just testing it out

#
    path("sign-up/", views.createAccount, name="create-account")
#

@astral thistle

#

i have pip install flask_sqlalchemy but i dont work

native tide
#

did you do that?

#

secondly, you have to import it like this

#
from flask_sqlalchemy import SQLAlchemy
astral thistle
astral thistle
native tide
#

how can i upload it how

edgy sable
native tide
limpid horizon
#

Hey I'm figuring that this is a terrible question but I'm asking anyway
Is there a course anyone knows that teaches one web-development until the point of an entry-level-job knowledge?

native tide
#

Trying to add Google maps into a project, anyone has done this before on python??? What's api key for Google maps thinking? Didn't get it.. I did something similar on c# but it was a little bit different...

limpid horizon
#

Well aware that experience, projects, and portfolios matter the most, just wanna know the people's input on this

vestal hound
#

I'm guessing you mean free and online course?

limpid horizon
#

Online? yes, free? Would be nice, but not limited to

#

I'd pay some solid cash for good education

#

I consider it an investment, of course I can study material by myself for free but definitely not in the same timeframe as a course would
Not me at least

#

I'm sure that there are ultra-geniuses here that can learn intermediate-level Django in a month but I'm not one of them.

vestal hound
#

that said, I honestly don't know

#

what good paid courses there are.

vestal hound
#

is to get a private tutor/instructor

limpid horizon
#

Hm, that is a good idea
I just saw there are pretty good online courses on Udemy/Coursera for not much money, I was wondering if anyone here has some experience with those

native tide
#

how can i change my text position in flask

limpid horizon
#

I didnt think about taking actual lessons though, I'll check if there are any where i live

vestal hound
vestal hound
#

a good instructor will not be cheap

limpid horizon
vestal hound
#

like, really not cheap

limpid horizon
limpid horizon
#

I'm good at studying by myself, It's just that web development specifically has some really complex concepts "behind the hood" and I would like to get a basic grasp on those too

limpid horizon
vestal hound
#

doing that kinda thing is really a "long-run" thing

#

that kinda thing = getting an actual person to teach you

vestal hound
#

what are you thinking of

limpid horizon
#

Umm... Let me see

#

I'll give an example as I'm trying to learn bottle right now after encountering some issues with Flask

#

Alright, here

#

I think that's a decent example:
So cookies - I know what they are, and generally speaking what they do.
I would like some practical knowledge on them - How they're used in modern technology, where they're stored, how they're ordered, how to access them properly

vestal hound
#

you want the surrounding knowledge

limpid horizon
#

I guess, yeah

#

It feels important, I don't know if it actually is

vestal hound
#

for example, the fact that a HttpOnly cookie is not accessible to JS

limpid horizon
#

See, I barely even know what you said

#

You're telling me there are types of cookies?

vestal hound
#

a flag you can set

#

to tell the browser

#

"don't let JS touch this"

limpid horizon
#

Right, and maybe the doc explains it further down the line

#

I just cant get my head around it if I dont know its basic mechanics

#

It's hard to accept that there is just text that I can save and access behind a user's browser

vestal hound
#

yeah, just an example

#

lots of stuff that's important to know

limpid horizon
#

Because I don't really know what to do with that knowledge and I cant get it inside my head.
And bottle is, and this is an understatement, not very supported. So I cant really find exercises* to test my knowledge on - so I invent my own experiments

limpid horizon
vestal hound
#

I honestly think

#

what you want

#

is not a course

#

but a mentor

limpid horizon
#

with mentors basically being private tutors

vestal hound
#

no

#

not necessarily.

limpid horizon
#

Oh, so?

vestal hound
#

a private tutor teaches you what you tell them to teach you

#

and then some

#

a mentor guides you in setting goals, reviews your progress, gives advice, etc.

#

they may also teach you specific stuff

#

but a lot of it goes towards easing the process of learning

limpid horizon
#

Uh, do people actually get paid to be mentors?

vestal hound
limpid horizon
#

To me it sounds like you might as well be a private tutor with that knowledge - they could probably offer the same services and then some.

desert egret
#

hello everyone

vestal hound
#

the canonical case is

#

someone senior (in terms of ability) to you

#

whom you know from work or socially

vestal hound
#

because private tutors focus on the technical material

#

but I sense that's not all you're looking for

#

you also want the big picture

#

things like industrial applicability?

limpid horizon
#

I just don't want to learn things "like a parrot" - To know that X code does Y and apply it

#

I really believe some basic background understanding is required in order to really understand what you're doing

#

I could have a completely false understanding of what web development actually is. Maybe the correct way, so to speak, is to just know what code does and that's it

#

I could just be delving into it a little too much, I'm not even sure if web development is what I want to do. You can correct me if I'm wrong

native tide
vestal hound
#

which is precisely why I say you need a mentor!

#

because

native tide
#

it makes sense now

#

btw

vestal hound
#

you don't just want someone to teach you webdev

native tide
#

@vestal hound pls help me

vestal hound
#

you want someone to help you chart your path, right

vestal hound
limpid horizon
#

That would be very nice, yeah

#

Where do I find a mentor though.

native tide
# vestal hound ?

so rn, my "create a note view" in my django app doesnt need authentication.

#

basically what happened was

#

i built the authentication part after the app itself

#

so its getting kinda complicated

vestal hound
#

that's the hard part, isn't it

native tide
#
from django.db import models
from django.contrib.auth.models import User


class UserProfile(models.Model):
    user = models.OneToOneField(User, primary_key=True, verbose_name="user", related_name="profile", on_delete=models.CASCADE)
    name = models.CharField(max_length=30, blank=True, null=True)
    bio = models.CharField(max_length=500, blank=True, null=True)
    location = models.CharField(max_length=100, blank=True, null=True)



class Note(models.Model):
    body = models.TextField(null=True, blank=True)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)


    def __str__(self):
        return self.body[0:50]
#
@api_view(['POST'])
def createNote(request):
    data = request.data
    note = Note.objects.create(
        body=data['body']
    )
    serializer = NoteSerializer(note, many=False)
    return Response(serializer.data)
#

this is the view that creates the note.

#

right now it doesnt need authentication as you can see.

#

what code should i add so that a certain user's note only appears to him

limpid horizon
desert egret
#

I'm not sure but you can try something like

vestal hound
desert egret
#
@login_required(login_url='login')
def createNote(request):
    data = request.data
    note = Note.objects.create(
        body=data['body']
    )
    serializer = NoteSerializer(note, many=False)
    return Response(serializer.data)```
limpid horizon
desert egret
#

You have to be logged in to be able to create a note and once you do that, use the pk of a the user to filter the notes when a user want to see only his notes

vestal hound
#

you can do that @ filter level

vestal hound
#

you can ask that kinda question around here

oak lion
#

how to make a working search bar with python that displays a page with the search results?(like https://udemy.com/)

vestal hound
#

how do you build a car?

oak lion
desert egret
#

actually I have a more simple problem that I resolved once but forgot how to do it again in django, can you help guys ?

vestal hound
oak lion
vestal hound
oak lion
#

am doing that

#

but what should i use

#

like django?

#

or anything else?

vestal hound
#

doesn't really matter

#

just get started

oak lion
#

oh

#

thnx

vestal hound
#

you're not @ the point you need to measure tech tradeoffs I think

desert egret
#

I have an app where users can see album and photos, but they have to be authenticated to be able to do that. In views.pyโ€จโ€จpython @login_required(login_url='login') def index(request): if request.user.is_authenticated: user = request.user username = request.user.pk album = Album.objects.filter(owner_id=username) contexts = { 'album': album, 'user': user } return render(request, 'client/index.html', contexts) else: return render(request, 'client/login.html')โ€จโ€จโ€จindex.html

{% if album %}
        <h2> Hi, {{ user.first_name }}. You have some photos             to choose from.
        </h2>
        <div>
            Click <a href="
                {% url 'client:album_details' album.id %}">here</a> </div>

    {% else %}
        <h2>
            Hi, {{ user.first_name }}. You don't have any photos uploaded yet.</h2>
        <div>
            Wanna book me ? Click <a href="{% url 'client:bookme' %}">here</a> </div>
    {% endif %}

urls.py

url(r'^user/(?P<pk>[0-9]+)/$', user_album_details, name='album_details'),

last but not least, the call to the user_album_details functions in views.py is :

@login_required(login_url='login')
def user_album_details(request, pk):
    album = get_object_or_404(Album, id=pk)
    return render(request, 'client/photo_details.html', {'album': album})```โ€จโ€จThe error :

NoReverseMatch at /client/user/

Reverse for 'album_details' with arguments '('',)' not found. 1 pattern(s) tried: ['client/user/(?P<pk>[0-9]+)/$']```

Partial solution:
if I replace album.id in index.html as follow :

<div>Click <a href="{% url 'client:album_details' 1 %}">here</a> </div>```
it works but with album.id or album.pk or even album_id, it doesn't work
limpid horizon
vestal hound
#

h

#

might not get na naswer but

#

@ leasty ou tried

#

๐Ÿ™‚

limpid horizon
true kernel
#

is defining STATICFILES_DIRS necessary? I havent defined it, and my image wouldnt show. Heres my code

#
{% load static %}
<img src="{% static 'base_app/image.jpg' %}" 
alt="My naruto">

image is in base_app/static/base_app/image.jpg

native tide
#

how can i change my text position

whole sierra
#

could anyone tell me how to add otp to an already establish login.html page. I.e. I've already configured the rest framework auth

native tide
#

is there a way to send a request to another route internally? Flask/Quart

eternal blade
#

Django rest framework question ```py
class SignupSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ("id", "username", "email", "password")
extra_kwargs = {"password": {"write_only": True}}

def create(self, user_data):
    return User.objects.create_user(user_data["username"], user_data["email"], user_data["password"])

``` I have this serializer, how can I dynamically add key to the serializers data?. I want to add a tokens key to the data which will contain the access and refresh token. Thanks

serene prawn
eternal blade
native tide
#

and when i put it in the code

#

err

serene prawn
jaunty magnet
#

Is anyone good at deciphering django error messages? I installed and configured django-rest-auth, double checked everything and still getting this error? I have the same set up on other recent projects and have not encountered this.

jaunty magnet
#

It says it's coming from within the rest-auth code though

#

which is hidden

#

since it is a package

serene prawn
#

Can you send it's github/pypi page?

jaunty magnet
#

yes hold on thanks for helping

serene prawn
#

It wasn't updated for 3 years though

#

And it probably doesn't support django 2 and 3

jaunty magnet
#

yeah that is a red flag, but I've made several recent projects using it andhavent had this problem

serene prawn
jaunty magnet
#

even used it last week

serene prawn
#

I guess it will work with django 1.8 ๐Ÿ™‚

#

try dj_rest_auth

jaunty magnet
#

i would try a different package or version normally, but kinda mind boggled at how it worked with the same set up last week, which is making me think its something else i did

#

ive only been learnin django for the last month so still getting used to debugging it. its hard

sonic island
#

Do I need to know a web server (apache nginx) for a django app?

serene prawn
#

For development built-in dev server would do

native tide
#

What's the way to set the flexbox width to it's children width

serene prawn
native tide
serene prawn
#

If you remove width rule then it should take width of largest child element

native tide
#

there isn't one tho

#
const InputContainer = styled.div`
    height: 300px;
    background-color: #00003F;
    display: flex;
    flex-direction: column;
    flex-basis: 0;
    align-items: center;
    justify-content: center;
    margin-left: 30px;
`
#

still being 100% width of the page

hushed cloud
serene prawn
#

@hushed cloud You can really learn all of that by yourself ๐Ÿคท

hushed cloud
#

๐Ÿ˜ฎ where

native tide
#

there are a bunch of free web tutorials

hushed cloud
#

wait by myself brainmon

hushed cloud
native tide
calm plume
serene prawn
#

If you need to pass data into your templates, just pass it as context when using render_template

#

Context processors inject variables automatically, so it might be helpful for something global e.g. functions or configs

#

I guess just to keep your code dry ๐Ÿ˜‰

#

As i see you can pass keyword arguments into render_template and they'll be available in your template

@app.route('/hello/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)
orchid olive
#

question, what is the best option to get the remote tcpip?

request.environ.get('HTTP_X_REAL_IP', request.remote_addr)

or just

request.remote_addr

?

serene prawn
#

@orchid olive
I believe if you're running behind a proxy remote_addr would be that proxy ip ๐Ÿ˜‰

serene prawn
#

Depends on if you have a proxy server and it's setup ๐Ÿ˜…

carmine cipher
#

Hello guys , please ,can someone explain to me how can I make my website online ?

lavish ferry
#

Hey so I wish I could make a more targeted question, though async requests seem really complex and I need some advice around how to start and what the steps more or less are for me to implement them. My goal is when someone clicks process on a form, the inputs are taken and some calculations occur, then the existing page will be updated with the result (rather than my current approach of refreshing the entire page and specifying the inputs again via Jinja HTML logic).
Here is the Flask back-end stuff currently:

#
# 101Cipher.
from validation import Cipher101Form
@app.route("/encryption/101cipher", methods=['GET', 'POST'])
def cipher101():
    form = Cipher101Form()
    if request.method == 'POST':
        if form.validate_on_submit():
            key = form.key.data
            number = form.number.data
            try:
                if form.encrypt.data:
                    result = encrypt_101(key, number)
                elif form.decrypt.data:
                    result = decrypt_101(key, number)
            except:
                result = "Process Execution Failed"
            data = {"key": key, "number": number, "result": result}
            return render_template('encryption/101cipher.html', title="101Cipher", form="submitted", data=data)
        else:
            errors = form.errors
            for form_value in errors:
                errors[form_value] = errors[form_value][0]
            return render_template('encryption/101cipher.html', title="101Cipher", form="failed", errors=errors)
    else:
        return render_template('encryption/101cipher.html', title="101Cipher", form=None)
#

The validation (for context):

# 101Cipher.
class Cipher101Form(FlaskForm):
    encrypt = SubmitField('encrypt', validators=[Optional()])
    decrypt = SubmitField('decrypt', validators=[Optional()])
    key = StringField('key', validators=[InputRequired(), Regexp('^[1-9]\d*$',
                                         message="Field must be a positive integer."),
                                         length(max=101, message="Field cannot be longer than 101 digits")])
    number = StringField('number', validators=[InputRequired(), Regexp('^[1-9]\d*$',
                                                                     message="Field must be a positive integer."),
                                             length(max=135, message="Field cannot be longer than 135 digits")])
#

So can anyone point me in the right direction please as far as how I can move away from this page re-rendering with parsed variables to dynamically updating the existing page?

#

I would greatly appreciate any help that can be provided here. ๐Ÿ™‚

little panther
#

there are many approaches to this. I guess the basic idea is to have an internal API endpoint that can be called by the front end when updating elements on the site on demand. https://htmx.org/ works well with flask, but you could also just use javascript to fetch the backend to get the data that should be updated to, then grab an element on the page to update it.

vernal wolf
#

!p django

lavish prismBOT
#
Bad argument

Converting to "int" failed for parameter "pep_number".

vernal wolf
#

-p django

little panther
nova sonnet
#

hey guys for model forms is there a way to make it so a select box will only show options depending on what group a user is in

#

for django

lavish ferry
#

Didn't find this option myself.

rotund perch
#

Token-Based vs JWT vs Django-Knox for Authentication. What is the best to use in case of security?

orchid olive
#

we can create a bot for discord, ok
can we create a bot for MS-Teams?

inland oak
# orchid olive we can create a bot for discord, ok can we create a bot for MS-Teams?
orchid olive
whole sierra
#

I know this is a stupid question, but my django secret key was leaked. Considering I'm going to just generate another one, that shouldn't matter at all once the site is live right?

inland oak
#

if site was not live, then you had no users which authentificated with this secret key, and you would not care if somebody could impersonate them

#

if your site is not using secret key in anyway, you could just make it randomly generated at every start ;b

import secrets
SECRET_KEY = secrets.token_hex(16)
fossil pond
#

Hey guys! My Django wesbite is running on an EC2 Windows instance and I want to get SSL certification for it. What is the best course of action for me to follow?

fossil pond
#

Specifically rerouting it to my domain

native tide
#

what type are current_user.role and roles.user?

#

if one is RoleEnum.user and the other is RoleEnum.admin then the condition won't be met

#

can you try
{% if current_user.role|string() == roles.user|string() %}

#

first answer on google

#

flask uses jinja2

#

as its template rendering framework

#

so if you have any questions regarding rendering of the templates just look it up and append "jinja2" to your search query

#

was they were not of the same type

#

that's why i asked you to verify the types of objects

native tide
#

i assume by default __repr__() method is called of current_user.role object

#

when you just reference it as current_user.role

#

in the template

#

you can read more into __repr__() and other special methods of objects online

#

whereas string() made it call __str__() instead

#

which returned the string identical

#

to what roles.user|string() returned

graceful flax
#

Hi,
I have users who can be reported and I need to save information of the report.
So my user report model looks like this

class UserReportLog(models.Model):
ย  ย  reported_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
ย  ย  reported_at = models.DateTimeField(auto_now_add=True)

should I add another foreign key to the user who was reported ? which will make it

class UserReportLog(models.Model):
    reported_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
ย  ย  reported_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
ย  ย  reported_at = models.DateTimeField(auto_now_add=True)

Currently there's a many to many field in the user model

userReportBy = models.ManyToManyField(
ย  ย  ย  ย  UserReportLog, related_name="userReported", blank=True
ย  ย  )

I'm not sure which is the best practice

swift wren
#

hey guys, im building a backend using flask and a frontend using react right. i dont have issues im asking for advice because the last time i kept going without planning i screwed up really badly with oauth. im using flask therefore my best guess is to use flask login but im not sure its not secure enough. what is the best system for authentication. also, how can i maximise the utilisation of sessions because im sure thats required in a application

native tide
candid panther
swift wren
#

plus, im positive i have more flexibility using python

#

if you can sell me, i'll consider it because ive been doing flask for a solid year now and i've produced 3 complete applications

candid panther
swift wren
#

therefore im solid in flask

swift wren
#

well, i didnt find spring boot kinda cool but its so bulky to me i feel like

candid panther
swift wren
#

xD i cant lie they are trash, just crud but i guess its the most that flask is required to display the main features of flask

#

im curious now because im building a actual applicaiton indented for the market

#

i feel like i should try spring boot

#

but idk, which one do you personally reccomend

candid panther
swift wren
#

which one do you think would be the best

#

in your opinion

#

im hoping you say spring boot becasue i cant stand c#

candid panther
#

According to me each tech stack has its benefits and cons, like the learning curve and support. Tech giant use java and .net because of there support by Oracle and Microsoft.

swift wren
#

well, i dont have a oracle or azure cloud services

candid panther
swift wren
#

man this is such a huge leap of faith, im hoping you know that

candid panther
swift wren
#

like ive done so much work within flask its insane

#

making a transfer is gonna be huge

#

i'll do it if it benifits me

candid panther
candid panther
swift wren
#

im building a ai based note-taking suite

#

on the fly kinda thing

#

another reason for python

swift wren
#

the best java has to offer for ai is deep java library

candid panther
swift wren
#

i was hoping to handle that using the flask server

somber seal
#

Anyone have any experience using Apple M1 for development specially when deploying to x86 Linux Architecture?

rotund bronze
#
GitHub

Monitoring Web App build using FastAPI. Contribute to YashIndane/monitoring-webapp development by creating an account on GitHub.

native tide
somber seal
# native tide Some. Depending on what you use, docker is your friend here.

It's just that most cloud platforms today are on x86 architecture so arm is pretty new to the space and was wondering if there will be any issues with libraries as in the past I faced issues before in a team that used Linux as their development machines where some libraries behaved differently on Mac and needed special tweaks in our docker scripts to be able to run correctly!

#

For example PyTorch is a big miss on M1.

#

I see when most people talk about Python development on M1, I feel like they are talking to the Junior developers that are trying to create a ToDo list. Yet as you get deeper the gap becomes bigger!

#

Another example not related to M1 but to macOS is that Apple stopped supporting "tap" drivers for VPN's which made our IT department have to switch to "tun" drivers so everyone can access the VPN!

warm igloo
#

It will only matter for things that are compiled. For instance, PyTorch isn't pure python afaik.

#

And the m1 is so new, but at end of day it is still ARM underneath (ARM 8 iirc). I've run into some problems with dependencies not working on M1s and .. well, will just have to wait for them to catch up.

somber seal
#

It feels like over time Apple will soon start blocking a lot of things and lock things only to their frameworks!

warm igloo
#

I mean, sure I guess. They do love their walled gardens.

#

They also dropped a shit ton of ports for a while and brought them back to newest laptops and called it innovation haha.

somber seal
#

@warm igloo Are you on M1?

warm igloo
#

Nah, avoiding it for now, but we've had issues at work with a client or two because of it.

native tide
#

I just started converting a personal project to all docker containers. My containers are aarch64

#

But running on an M1 mac

warm igloo
# somber seal Can you explain?

We have a client having issues getting the OSS they have built a company around running on a M1. We're working on it with them a little, but its not exactly an emergency cause sure devs can't run it on an M1 but none of their clients are trying to get it running on that hardware for real. So it'll eventually get fixed.

#

So for now we're just not buying M1s if new folks join (and we're hiring quite a bit). Eventually maybe, but I always like waiting out new things from Apple anyway.

#

If I have my way, I'll be leaving my Mac behind anyway and going to a Linux dev machine which I haven't used professionally since OSX debuted.

#

I mean: I use Linux daily, just not as my dev machine.

somber seal
# warm igloo If I have my way, I'll be leaving my Mac behind anyway and going to a Linux dev ...

Yea I've been using macOS for a long time now, but after all this Apple Silicon stuff I started to think the server space isn't going to catch up any time soon. And this makes maintenance issues as arm architecture has to be supported. So I sold my MacBook Pro and have been working on a Linux box for a couple of months now and its been smooth sailing TBH. Yet I was also looking at WSL2 specially on Windows 11 with Linux GUI apps and GPU pass-through looks really nice!

#

The only thing I like about the new MacBook's so far is the battery life and how quite they are!

primal hound
raw dew
#

What the best Library for Web Develop? (Atleast for beginner)

chrome wren
#

hi, anyone knows how to check when was a page's code changed last?

#

basically, i have a url from a specific, high profile page

#

and a little bit of code was added

#

and if i can confirm the date it was added, i may make a lot of money out of it. so, anyone knows?

fickle garnet
#

way back ? loll

chrome wren
granite plinth
native tide
#

hello

#

i am using tailwinds css

#

to make my website

#

i want to replace

#

<svg

        xmlns="http://www.w3.org/2000/svg"
        fill="none"
        stroke="currentColor"
        stroke-linecap="round"
        stroke-linejoin="round"
        stroke-width="2"
        class="w-10 h-10 text-white p-2 bg-indigo-500 rounded-full"
        viewBox="0 0 24 24"
      >
        <path 
          d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"
        ></path>
      </svg>
#

the tailblocks stock image

#

with this

#

where should i?\

#

oh nvm

#

figured it

#

oit

#

out*

fickle garnet
wooden ruin
flint field
#

anyone know why my navbar at the top does not fully show up on mobile

#

computer:

#

Mobile:

#

code:

<!doctype html>
<html>
<head>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title>{% block title %}{% endblock %}</title>
    </head>
    <body>
        <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <a class="navbar-brand" href="/">Home</a>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav">
            <li class="nav-item active">
                <a class="nav-link" href="/bin">Lowest BIN</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="/username">Username checker</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="/thesaurus">Thesaurus</a>
            </li>
            </ul>
        </div>
        </nav>
        <p></p>
        
        <h1 style="text-align:center;font-family:Goudy Stout">
            <font color = "#003078">
                {% block heading %}{% endblock %}
            </font>
        </h1>
        {% block content %}
        {% endblock %}
        <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    </body>
</html>
wispy quail
#

For fastapi testing, how do you generate responses via schemas?

#

or any good tutorials for testing fatsapis beyond the docs?

weary wharf
#

jinja2.exceptions.UndefinedError: 'form' is undefined

#
<!-- Form rendering is simple and easy if using bootstrap -->
<div class="col-md-6 ml-5">
{{wtf.quick_form(form)}}
</div>
weary wharf
#

I did do {% import "bootstrap/wtf.html" as wtf %}

#

but still get this error

grave raft
#

headers = {'Authorization': 'Bearer ' + accessToken, 'Content-Type': 'application/json'} r = requests.post('https://www.googleapis.com/upload/drive/v3/files?uploadType=media' , headers=headers, files={"test2.pdf":fileData.getvalue()})

#

I am trying to upload a bytesIO file object to google drive as pdf
It is being uploaded in this wrong format ... but file size is correct

#

I can't figure out in which format should i convert ... any idea??

#

Thanks

thin lance
#

Hi everyone, is there anyone who works with FastAPI?
I am working on the development of register-api for that I use fastapi, Python-Keycloak and docker, I am currently learning middleware and I am interested in where you would use middleware and why?

#

I hope the question is not stupid ๐Ÿ™‚

languid beacon
#

hey

#

anyone good in react?

fathom fjord
#

hi

#

anyone here?

winged orbit
native tide
#

this is the view that creates an account

#
@api_view(["POST"])
def signUp(request):
    data = request.data
    username = data["username"]
    email = data["email"]
    password = data["password"]
    user = User.objects.create_user(username=username,
                                 email=email,
                                 password=password)
    return Response("Account Created!")
#

im getting an error saying 403 forbidden

candid meteor
#

I need some quick help

#

need someone to register an account on my website for this new authentication, ive run out of gmail accounts to test myself

#

please ping me for the link

unkempt temple
candid meteor
#

Its in my about me incase you can help test

native tide
#

like this: ```html
<script src="utils.js" />

frank shoal
#

anything in the console?

#

Oh. You can't do <script /> It has to be <script></script>

native tide
frank shoal
#

Was there anything in the console? (press F12)

#

or Ctrl+Shift+I in chrome

native tide
frank shoal
#

Click it and check if the location is correct

native tide
#

nothing in utils.js

junior aspen
#

I heard that python is not that much used in web dev, m I wrong?

frank shoal
#

Yes. There are several frameworks for web dev

#

django, flask, fastapi, etc

frank shoal
native tide
frank shoal
#

What did you change it to?

#

Does it have a line number?

native tide
#

<script src="#templates/utils.js" />

#

to this

frank shoal
#

That's the full text?

#

Are you using a framework?

native tide
frank shoal
#

because hashes don't get sent to the server.

#

You're basically asking for the same page

native tide
#

where can i add the code

#

i will send you the html and css

frank shoal
#

<img style="float: right">

#

or if the left side is in a div, add a inline-block div after it.

frank shoal
native tide
frank shoal
#

use <script src="{{ url_for('static', "js/utils.js') }}" />

#

assuming utils.js is in static/js/utils.js

native tide
#

it came on top

frank shoal
#

You didn't make it inline-block, and you didn't put it on the bottom

#

this is assuming you aren't using any fancy flexboxes

native tide
#

why is the h1 coming in red?

frank shoal
#

put the img tag after the article tag

#

and style it with style="display: inline-block;"

native tide
#

const chat = document.getElementById('myChart').getContext('2d');
jinja2.exceptions.TemplateSyntaxError: expected token ',', got 'chat'

#

i have to go

#

i will come back later

frank shoal
native tide
#

this is the code ( it doesnt have the things you asked to add)

#

can you tell where exactly should i add and what to add

frank shoal
#

should be after </article>

#

What's with </aside>?

#

That's not a valid tag

#

and you never open it

serene prawn
#

aside is a valid tag though

frank shoal
#

It's still never opened

serene prawn
#

But it's valid ๐Ÿ™ƒ

frank shoal
#

Dang. It isn't even html5. it's old

sweet drift
#

!voiceverify

tender zenith
#

Is it easier to use python to write a web app that gathers data from clients
or is it easier to do that with Google Apps Script?

#

The website already has an front-end and they used React

outer apex
simple garden
#

does border bottem transition work in css

candid panther
#

Anyone who knows threaded data dumping?

deep monolith
#

Are these prices expensive for website hosting / ssl ?

glacial yoke
#

Hey, can someone send me a config file for the daphne startup file, which would work well with django?

#

Because what I have doesn't seem to work:

#!/bin/bash

NAME="project-daphne"  # Name of the application
DJANGODIR=/home/admin/code/project/mysite# Django project directory
DJANGOENVDIR=/home/admin/code/project/env  # Django project env

echo "Starting $NAME as `whoami`"

# Activate the virtual environment
cd $DJANGODIR
source /home/admin/code/project/env/bin/activate
source /home/admin/code/project/mysite/.env
export PYTHONPATH=$DJANGODIR:$PYTHONPATH

# Start daphne
exec ${DJANGOENVDIR}/bin/daphne -u /home/admin/code/project/env/run/daphne.sock --access-log - --proxy-headers mysite.asgi:application
warm igloo
#

But SSL can often be free via LetsEncrypt depending on your setup.

deep monolith
#

our org is paying for a wordpress host, the company hosting is not doing website maintenance

glacial yoke
#

I'm only paying like 10$ per year for my ssl certificates

warm igloo
deep monolith
#

just wanted to make sure were werent getting horribly shafted

native tide
#

Some genius here that already had contact with DRF and NGINX JWT Authentication (subrequest calls against auth service). Please also see:

https://stackoverflow.com/questions/69802080/how-to-pratically-deliver-hls-streams-that-are-stored-on-s3

runic sparrow
#

Could someone please recommend an authentication system for a web app I'm building? I don't know whether I should use flask-login or do my own implementation. I feel like I might learn more doing it myself, but I'm worried about security and I probably shouldn't reinvent the wheel.

If I am to go with flask-login, should I learn and use flask-sqlalchemy or use plain old sqlalchemy instead (or even sqlite3 or similar)? Online, I've found some contradicting info on this from some pretty reputable sources.

Thanks in advance!

left summit
calm plume
#

That's completely up to you. If you prefer the apis one or the other provides, then use that.

#

As for the login, it's pretty easy to get it secure, just hash things with a proper algorithm (like bcrypt for passwords)

#

I wouldn't use a library myself

left summit
calm plume
#

In a database like postgres

runic sparrow
#

Ok, thanks! Would you recommend using sqlalchemy or sqlite3/aiosqlite? I don't want to go down the wrong route and shoot myself in the foot, and I'm still relatively new to SQL

left summit
calm plume
#

I'd use sqlite only if it's a rather small project

left summit
#

i prefer json style database

#

i know its not a good think but i find it more flexible in projects

calm plume
#

You prefer NoSQL? I love relations myself.

left summit
calm plume
#

I'd hardly say it's inflexible, you can do quite a lot with SQL databases

runic sparrow
#

I doubt it'll ever end up as anything big ||(i never actually finish anything)||, but it's good to have scalability, I guess? What's the issue with using sqlite?

left summit
calm plume
left summit
#

according to mmy website host its harder to host dynamic websites than static ones

calm plume
left summit
calm plume
#

Uhh, nosql still needs hosting

#

Which nosql db are you using?

left summit
left summit
calm plume
#

That's false. It's just that firebase is hosting it for you.

left summit
calm plume
left summit
#

so i dont have to set it up myslelf

left summit
#

where were you all these dayss

#

thank you so much

#

bruhhhhhhhhhh

#

i thought these never existed

#

im too used to noSQL to go to this but its on my learning chat

runic sparrow
#

oh wait, I've replied ultra late

#

i blame bugcord

left summit
#

i hope you can make youre website in peace now

#

knowing ddifferent opinions on a topic

runic sparrow
#

Thanks! I'll have a shot with sqlite

left summit
#

haave fun

runic sparrow
#

...just checking, it is fine to use sqlite3 instead of aiosqlite, right? Do web apps have to be asynchronous?

#

Logically I feel like yes, they do, but I haven't seen any async syntax yet

left summit
#

but im not the guy for the sql questions

#

gn my kind sir

runic sparrow
#

Thanks a lot!

calm plume
runic sparrow
green prairie
#

Guys - I'm really in two minds of whether I should use Supabase with FastAPI - Or I should completely ditch Supabase and build authentication and stuff directly in FastAPI

#

Can someone come with some inputs in that decision? โค๏ธ

calm plume
#

That's really up to you. Do you like Supabase's way of handling auth, or would you prefer rolling custom?

green prairie
#

I haven't worked a lot with Supabase - But I suppose they take a lot of the headaches out of it?

calm plume
#

They do make it slightly easier, so here's my input. If you want to go with OAuth providers or magic links, go with Supabase Auth. If you'd rather use the traditional email/password approach, roll your own as per the FastAPI tutorial.

green prairie
#

Alright - Thanks. I think I'll go with Supabase then. Hopefully changing it won't be too hard, if I decide so (even though I've heard otherwise)

native tide
frank shoal
#

It depends

native tide
#

whats wrooooooooong

#

i am stuck on this for like 3 days

frank shoal
#

Post your template file

frank shoal
#

I don't think browser supports exports

#

Everything just gets added to the global namespace

#

You also shouldn't mix src with a script body

native tide
#

sooo what should i do?

#

@frank shoal

frank shoal
#

It depends on what utils does

frank shoal
#

Can't use imports in the browser.

#

You'll need to build it using a tool like webpack

#

To export functions with that, just set it on window

frank shoal
#

window.foo = foo;

native tide
frank shoal
#

In place of exports

#

But you still need to use webpack to build your app

native tide
#

why its so complicated

frank shoal
#

No webpack or node/npm needed

sharp valley
#

I need help with this please help with this web development help

frank shoal
#

Spiders?

#

I suggest fire ๐Ÿ”ฅ๐Ÿ”ฅ๐Ÿ”ฅ

little panther
# native tide to this

can you paste the full code please? the basic idea is to have chartjs's utils.js source (you can find it by searching utils on their docs) and put it in a file. Then in your previous <script> where you made the graph you have to use import to import the file and have the module accessible in Utils. It won't work if you only have a single <script src=.../>

vocal sparrow
#

why print statements inside django doesnt print anything , what makes em not print stuffs

native tide
#

try

#

print("something", flush=True)

left summit
#

hello

#

does anyone here use a webbuilder then externally change the code by adding in javascript file

left summit
full birch
#

Hello

#

Someone there!?

native tide
#

ask away

foggy bramble
#

Can someone explain me why should one use celery +rabbitmq instead of using just fastapi background task

inland oak
# foggy bramble Can someone explain me why should one use celery +rabbitmq instead of using just...

celery master that takes orders can be one Server. Master just puts the task in a job queue.
and Workers that process tasks can be N amount of other servers. They just watch the queue and complete the tasks based on the availability
workload quite good distributed between multiple servers. Better scalability for serious business ๐Ÿ˜‰

Plus all the code written for the background task being as comfortable as possible.
With reporting its intermediate progress and results.

foggy bramble
foggy bramble
inland oak
foggy bramble
inland oak
#

I could rip the necessary code parts though

#

hmm, too much to rip

#

or not

#

anyway, the core is folder with django settings

settings.py

from .celery import REDIS_HOST_RESULT, REDIS_PASS

# django setting.
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": f"redis://{REDIS_HOST_RESULT}:6379/0",
        "OPTIONS": {
            "PASSOWRD": REDIS_PASS,
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "IGNORE_EXCEPTIONS": True,
        },
    }
}

CELERY_TASK_TRACK_STARTED = True
CELERY_TASK_TIME_LIMIT = 30 * 60
#

file celery.py

import os

from celery import Celery
import time
import secrets
import subprocess
import sys
import redis
import base64
import json

# from .settings import CELERY_CACHE_BACKEND

# Set the default Django settings module for the 'celery' program.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings")

from dotenv import load_dotenv
from pathlib import Path
import secrets
import contextlib

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

load_dotenv(os.path.join(BASE_DIR, ".env"))

REDIS_PASS = os.environ["password"]
REDIS_HOST_QUEUE = os.environ["queue"]
REDIS_HOST_RESULT = os.environ["result"]
# celery setting.
CELERY_CACHE_BACKEND = f"redis://:{REDIS_PASS}@{REDIS_HOST_QUEUE}:6379/0"  # 'default'

app = Celery("core", broker=CELERY_CACHE_BACKEND)

app.config_from_object("django.conf:settings", namespace="CELERY")
REDIS_RESULT_FULL_ADDRESS = f"redis://:{REDIS_PASS}@{REDIS_HOST_RESULT}:6379/0"
app.conf.result_backend = REDIS_RESULT_FULL_ADDRESS
app.autodiscover_tasks()

# custom redis
redis_conn = redis.Redis(host=REDIS_HOST_RESULT, password=REDIS_PASS, port=6379, db=0)


@app.task(bind=True)
def debug_task(self):
    print("starting task")

    time.sleep(1)
    self.update_state(state="PROGRESS")
    return "123"
#

you add tasks to it in your views

from core.celery import debug_task

@api_view(["GET"])
def get_ping(request):
    task = debug_task.delay()
    return Response({"message": "pong!"})
#

master and worker nodes are initialized differently at different servers, but essentially to the same project

master:
    venv/bin/gunicorn core.wsgi -b 0.0.0.0:8000

slave:
    venv/bin/celery -A core worker -l INFO
#

@foggy bramble boop

foggy bramble
inland oak
#

I used only official docs

#

using RabbitMQ is more preferable than Redis, but I just used already Redis before so decided to less learn a bit

left summit
#

!d

lavish prismBOT
sharp valley
#

Ok can someone help me learn we development I need help iam a lil new

vernal thistle
#

Hi all. I am trying to make a flask app where I have toggle button which when clicked will change an entry in the database. How would I go about doing that?

All I can do currently is take input from a (text) form and change database based on that.

flint field
#

I am trying to make a part of my website automatically change each day. I am trying to pass the home page function a list but dont know if its possible. Would storing the list as a file be the best option

golden bone
vernal thistle
golden bone
vernal thistle
#

yeah

foggy bramble
#

Do i need to create database table manually in mysql database or below code in fastapi will create the database table if it doesn't exist?

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    email = Column(String, unique=True, index=True)
    hashed_password = Column(String)
    is_active = Column(Boolean, default=True)
    items = relationship("Item", back_populates="owner")
swift wren
limpid horizon
#

Is knowing HTML CSS and JS useful for web development or can you do without em'?

#

In the context of Python frameworks*

swift wren
#

short answer- yes

limpid horizon
#

Dont spare me any details if you can

swift wren
#

long answer, you always need some sort of css or html, in python context. js is needed if you need to get html information but for you, its not needed as python is handling everything through the jinja templating. css is sometimes needed but nowadays we have things like bootstrap, tailwind and bulma where you can produce bare css with just defining class names. html is needed to structure your site as python doesnt have a frontend framework but if you use react then you'll need the most bare amount of html otherwise if you're doing backend serving then you need to know html and css but then again

sharp valley
#

@swift wren when can we start ?

swift wren
#

as soon as you ask the question

limpid horizon
#

@swift wren Huh, so if you know Jinja and Bootstrap, HTML will do fine?

swift wren
#

if you're using jinja to render your html, the template is gonna be static so yeah basically

limpid horizon
#

I've been looking at tutorials and they always end up copying and pasting Gibbirish-looking blocks of code made out of the aforementioned languages

#

@swift wren Oh, thats pretty limiting though, no?

swift wren
#

learn flask. the best webdev framework imo

#

and i've worked with django and spring boot, spring boot is fire compared to django but its java based and java doesnt have a whole lot of python-esk toolkit

#

for me personally in a certain circumstance

#

but still, flask has been the easiest and to-the-point framework

#

its so good

#

and it has like insane extension modules

limpid horizon
#

Dont you reckon that if, at some point, you'll want a career in web development, you're better off just doing JS with Node.JS?

swift wren
#

justify that

limpid horizon
#

Hm?

swift wren
#

justify it, why do you think that

foggy bramble
#

No i dont

#

I found it

swift wren
#

db.create_all

foggy bramble
#

meta.create_all(engine) does the job

swift wren
#

and that will create all your tables

#

lol

foggy bramble
limpid horizon
#

Because if websites are built out of HTML, CSS and JS, those have the homefield advantage so to speak.
What I mean by that is that, if you're new to the field, the learning curve will be a lot more linear.
You make the template with HTML
Stylize them with CSS
and make interactions with JS
whereas with Python you'll first need to learn Python, and then Flask, and while you learn Flask you'll need to learn Jinja and bootstrap
So essentially you're first learning the backend, and then the frontend

foggy bramble
#

Yea

limpid horizon
#

Sorry about the block of text

swift wren
#

thats not correct

#

i can see your perspective and its personal as well but its just fallacy talking about learning curves as node.js and js in general has a steeper learning curve than flask and jinja

#

the complexity difficulty is abhorrent compared to node.js when producing complex web applications

#

with js you need to require like 12 different modules where as a simple flask import gives you all the tools necessary to produce a enterprise application

limpid horizon
#

Hm, I honestly dont know the slightest thing about Node.js, so I'll take your word for it
So in that case, wouldn't you agree that its still easier to learn HTML, then CSS, then JS and then* if you want, Flask or Django?

swift wren
#

i would never use node

limpid horizon
#

Yeah, no node

swift wren
#

i would never use express or http. just digusting tbh, im using react tho, react is kinda fire cos i hate writing html and i have to use axios to make requests.

#

i've produced mad applicaitons using flask and html

#

but now im using flask as a api backend and using react for frontend

#

makes everything lighter and faster

limpid horizon
#

Node.js uses react too no?

swift wren
#

no react uses js

limpid horizon
#

Oh

swift wren
#

wait

#

the thing is node is a runtime for js

#

there is v8 engine and there is node.js engine

#

but node comes pre installed with http library which gives node its label

#

but node.js is local js runtime

limpid horizon
#

Woah you lost me, this is way beyond my bracket of knowledge

#

Its interesting to know there are alternatives to JS and stuff, didnt know

swift wren
#

dw, js is the most sacriligious language ever. id reccomend you learn flask straight up. just generally stay away from js.

#

js is a bunch of rules that much be followed by a runtime

#

where has python, cpp and java have thier own compilers and interpreters

sharp valley
#

ok iam ready what software do i need

swift wren
#

idfk

sharp valley
#

man i thought u was gone help me

grave nexus
#

hey could i jump in and ask a question?

sharp valley
#

yea

grave nexus
#

ok,

#

so i need to build a web project that generates word reports for this department at work

#

it takes in input for the document through forms asking the various questions

#

the project is supposed to have these features:

  • user logins and different privileges depending on rank,
  • allow multiple people to work on the same project at the same time, and
  • have a log of what changes were made and by whom
#

so I know a HTML and CSS, plus a little bit of PHP

#

the main question is should i build the backend of this in PHP or Django or something like Go?

swift wren
#

go and see which library/framework looks easier to write

#

imo php is the easier out of those options

#

but im a huge advocate for flask

#

you can make whole applications in just one file

grave nexus
#

yeah, this guy at work says that Django and flask should be pretty useful

#

plus i know some python already

sharp valley
#

@swift wren can u hit me in the dm or help me here or some one i need to know how to do this or does any one know how to make a sneaker bot i need this done before December

swift wren
#

flask is the be all and end all for beginner and intermediate developers

#

also advance but im sure they venture way further away from vanilla flask

grave nexus
#

and flask will work for those three features i need?

#

even the word doc generation?

swift wren
#

you should be able to figure it out

#

django and flask are wsgi

#

its not a software its a frameowrk

#

all the logic comes internally, there isnt really any framework that does things for you

grave nexus
#

let me look into flask some more

lavish ferry
#

Hey is there a way I can (using a Flash backend) update colours in CSS?

lavish ferry
#

I want to avoid specifying colour in style on all HTML and then passing colour variable.

grave nexus
#

thanks @swift wren

hoary brook
#

@grave nexus
From my experience I can say that Django was indeed too much for a beginner, but Flask was easy to learn and very effective. Not sure how to do dynamic updates (e.g. when 2 people work on a document you can see the other person type like in Google Docs), but everything you mentioned is easily doable. Setting up models in quite easy too as long as you don't have too complex relationships.

lavish ferry
swift wren
#

nah its just values

grave nexus
#

plus i'm sure i could come through and ask if i get seriously stuck

hoary brook
lavish prismBOT
#

Hey @swift wren!

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.

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

hoary brook
swift wren
#

it was 3am, i was done with life. just wanted it finished

hoary brook
#

With Eel you can directly pass variables between JS and Python, just set up 2 functions and you're good.

swift wren
#

but you could have a array with the color values and just index and feed that to the iteration

lavish ferry
#

I have like no JS knowledge. All I know is I have my python backend which serves HTML templates which have associated colours defined in CSS.

swift wren
#

why would you use js

lavish ferry
#

Yes I see that I can manually specify style variables everywhere and pass a variable for the colour that way. Wouldn't it be more logical to update the CSS somehow?

#
hoary brook
#

Yes, as I said you set up a JS function that accepts a variable and modifies the CSS of an element, expose that function to the Python side using Eel and on the Python side have an exposed function that sends the color variable over to the JS side. https://github.com/ChrisKnott/Eel

GitHub

A little Python library for making simple Electron-like HTML/JS GUI apps - GitHub - ChrisKnott/Eel: A little Python library for making simple Electron-like HTML/JS GUI apps

#

I'm not sure if this will work, but I recommend you give it a try. If not, you might have to stick with hardcoding.

lavish ferry
#

Hmmm alright I will look into that.

#

Thank you Remy

sharp valley
#

So know one can tech me how to code or make a sneaker bot ?

left summit
#

im being very helpful #WILL BE A HELPER SOON XD

fickle garnet
sharp valley
fickle garnet
#

awesome, so you need an intro to programming in python course. i linked you to the lobby channel with pinned intro courses there @sharp valley

solar obsidian
#

im confused as heck

#

yesterday my site worked perfect

#

today the background image wont show up

#

it's in the folder with all the other images but

#

but flask wont serve it

#

wait nvm

lilac yarrow
#

@solar obsidian, did you fix it?

solar obsidian
#

yes but no

#

it turned out i replaced a css file which had a 1 at the end of the name

#

but i changed that and it's still looking for the file with a 1

lilac yarrow
#

@solar obsidian, hmmm... have you tried making any changes in your code itself, so that it's no longer looking for a file with a '1' at the end of its name??

solar obsidian
#

if add a 1 to the end of the name it works

#

but i cannot find anywhere where it's referencing 1

#

ahhh it's a cache

#

chrome is showing the old css

#

now it works

lilac yarrow
#

@solar obsidian, yeah, try cleaning your cache and refreshing the page, see what happens

lilac yarrow
frank shoal
#

ctrl+shift+r to refresh without cache.

#

If your networking debug tab is open, cache is disabled by default

#

in firefox at least

solar obsidian
#

how do you make a debug tab

frank shoal
#

Ctrl+Shift+I

#

or F12

solar obsidian
#

oh that just shows inspect element

frank shoal
#

there's more tabs than that.

#

You may be familiar with the console.

solar obsidian
#

well yeah it opens all that

native tide
#

how to execute console js through python?

viscid spade
#

How do I set the environment for flask

#

just downloaded yesterday using pip

#

?

#

Any one here

#

All I see is water

frank shoal
#

use environment variables.

dusk portal
#

@opaque rivet ๐Ÿ‘€

#

it's been a long day

#

i mean months

frank shoal
#

in bash, it's as simple as FLASK_APP=your_app flask run

median compass
#

Hey everyone

@app.websocket("/")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        connection = mysql.connector.connect(host='localhost',
                                            database='survey',
                                            user='....',
                                            password='...')
        data = "select Question_answer from user_questions where question_id = 2"
        data_cursor = connection.cursor()
        data_cursor.execute(data)
        query_data= data_cursor.fetchall()
        df = pd.DataFrame( [[ij for ij in i] for i in query_data] )
        df.rename(columns={0: 'Name', 1: 'Players'}, inplace=True)
        df['counts'] = df['Name'].map(df['Name'].value_counts())
        structured_df=df.drop_duplicates(subset=['Name'])
     

        data = structured_df.to_json(orient='records')
        print(data)
        time.sleep(10)
        await websocket.send_text(data)

what I'm trying to do is, keep the connection alive so when new data comes, It sends it to the server to update, however what's happening is once I establish connection in this function it'll always be running HERE, only. I have another page, with a normal GET request, if I go there the data I'm sending in the other page won't be there bec it's stuck in this while loop

surreal portal
#

Yo i meant to ask since Idk where webscraping and API fetching goes in but, does anybody know public APIs with job offers?

fickle garnet
fickle garnet
median compass
#

hmmmm check if I need to open a connection means I'll wait for something, something like a GET request right? is that do-able inside a websocket function?

fickle garnet
#

no idea. but read data, close data, prompt user, open data again to write... break up the function maybe..

surreal portal
fickle garnet
surreal portal
#

Thanks

near ore
#

I am front end developer with 1 year of experience and i am new to python.
I use python because i am working on side project which depends on open source which built on python

my question what is the right path to become python web developer.

native tide
#

first getting comfortable at python basics, then going through some crash course on the way websites work (even some front-end developers with experience dont have a clear idea), then choosing python library for full stack development and learning it, while making some simple test websites

#

most prevalent ones are django and flask

#

you can go with either one, personally i'd say flask is easier

#

you can find free python course on udemy

#

should be first link when you just search "free python"

near ore
#

thanks for your response

#

crash course on the way websites work do you suggest one

#

?

native tide
#

i know there are some good ones on yt

#

find some playlist

#

literally search "how websites work"

#

and find one that goes at least semi in depth

near ore
#

thanks

dim wolf
#

hi! i'm using django for a small project... should I reuse the same venv for other projects too ? or does each project need a new venv?

rocky current
#

It's best to make a venv for each project

#

Typically, you can put the venv directory inside the directory in which you hold the code, then exclude it from git with your .gitignore file.

#

If you do it that way, VS Code (and probably other editors) will detect the venv as being in the project and use it as the python interpreter.

dim wolf
#

it seems to get confused and if I activate one venv, then try to switch project to another it saying that python or other modules aren't found

#

so you need to install all the requirements and packages fresh on every venv or can they share?

rocky current
#

Its best if you do it fresh for each project, that way if you need to change modules in your venv you don't mess with any of the other projects

#

If you have your requirements saved to a file, you can have pip load them up all at once by running pip -r <filename>

dim wolf
#

ok thanks! my projects folder are a bit all over the place good reason to tidy it up

#

i used a list of like ~400 packages that were listed in anaconda environment so it took a long time to set up the one venv

rocky current
#

Definitely a good habit to get into! I make a directory called "Code" and put all of my projects in there. Each project has a git repo associated with it, with the requirements.txt file so it's easy to set up again later.

dim wolf
#

but maybe only installing those in use would be better

rocky current
#

Yeah, that could take a while. Definitely better to keep clean!

dim wolf
#

i've made it a bit too complicated like.. i have set up the one /code/venv ... then set up some folders like /code/python/frameworks/django/project/files/etc

#

should be simpler!

carmine cipher
#

Hello guys , How can I get a free domain for my website ?

native tide
solar obsidian
#

i copied a html file and renamed it

#

but flask isn't serving the css or images

#

for that page

#

but it serves just fine for the original

native tide
#

how to put range here ??

chilly garnet
#

Is there anyway to set-up django to automatically set the size of admin formfields based on the model field's max-length? Instead of manually adjusting it for every charfield?

native tide
#

And there are others

solar obsidian
#

BRUH

#

it doesn't serve anything

#

even if i set it to the EXACT same html file

#

it doesn't serve the images or css

#

just this page

#

everything else works fine

native tide
#

Did you look at how to serve static files with flask?

#

You have to serve them differently than templates if I recall

solar obsidian
#

i put the htmls in the templates

#

and the assets such as images and css in static

#

everything works

#

but not this one page

#

even if i serve the same html file

native tide
#

maybe relative paths or something

#

is the html file in a different path relative to the static stuff

#

oh hard refresh in the browser so you don't use cache

solar obsidian
#

i have

#

even opened other browsers

#
@app.route("/dashboard")
async def dashboard():
    if not await discord.authorized:
        return redirect(url_for("login"))

    user_guilds = await discord.fetch_guilds()
    guild_count = await ipc_client.request("get_guild_count")
    guild_ids = await ipc_client.request("get_guild_ids")

    guilds = []

    for guild in user_guilds:
        if guild.permissions.administrator:
            guild.class_color = "green-border" if guild.id in guild_ids else "red-border"
            guilds.append(guild)

    guilds.sort(key = lambda x: x.class_color == "red-border")
    name = (await discord.fetch_user()).name
    return await render_template("dashboard.html", guild_count = guild_count, guilds = guilds, username=name)

@app.route("/dashboard/<int:guild_id>")
async def dashboard_server(guild_id):
    if not await discord.authorized:
        return redirect(url_for("login"))

    guild = await ipc_client.request("get_guild", guild_id = guild_id)
    if guild is None:
        return redirect(f'https://discord.com/oauth2/authorize?&client_id={app.config["DISCORD_CLIENT_ID"]}&scope=bot&permissions=8&guild_id={guild_id}&response_type=code&redirect_uri={app.config["DISCORD_REDIRECT_URI"]}')
    return await render_template("dashboard.html")``` take a look
#

ignore the fact i dont send the variables

#

that shouldn't be a problem

native tide
#

and what's the template?

#

presumably it has paths to css and images and that's what isn't loading, right?

solar obsidian
#

yeah

#

but it's the same html requesting the same css

#

unless it's because it's dashboard/guild_id

native tide
#

I'd say if the template needs variables, you should pass them. and you're sure the first one isn't cached and that's why it "works"

solar obsidian
#

but it's not trying to find the css in /static/dashboard/.css

#

is?

solar obsidian
#

same thing

#

ahhh dang i was right

native tide
#

when you view source on both does it show that it's looking for css in the same place

solar obsidian
#

it's looking for the folder dashboard/static

#

just because that's the url why does it have to

#

i wish i could make it relative to the py file

native tide
#

the best

#

I think there is a way to serve all static from one location and point everything at that. Not sure how flask does that now, since I mostly live in the django world.

umbral crypt
#

Using dockerfile for the first time.. when running the command docker-compose up I get the error:
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?

Yet when I run django-admin --version I get proper feedback.. any ideas anyone?

olive tiger
umbral crypt
#

Hmm, I'm following the Django for professionals book and this is the yml file they listed:

version: '3.8'

services:
  web:
    build: .
    command: python /code/manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - 8000:8000
#

confusing

olive tiger
#

can you show Dockerfile?

umbral crypt
#

Sure

# Pull base image
FROM python:3.9.6

# Set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# Set work directory
WORKDIR /code

# Install dependencies
COPY Pipfile Pipfile.lock /code/
RUN pip3 install pipenv && pipenv install --system

# Copy project
COPY . /code/
olive tiger
#

check in the container, if your django is installed

#

I am not sure what pipenv install does

native tide
#

It's installing what is in the pipfile

#

do you have django in the pipfile

#

But...it makes a virtual environment

umbral crypt
native tide
#

so you can activate it in your build or try changing your command to:
pipenv run python ...

#

or at the end of your docker file you can try:
pipenv shell to activate it

umbral crypt
#

I tried that, I wonder if this has anything to do with it:
When I run django-admin --version I get this at the end

Note that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.).
olive tiger
#

I would not use pipenv in general

#

simple venv + pip-tools work better for me

umbral crypt
#

agreed

#

meantime I'll study up on docker

olive tiger
#

I use it in the container

#

instead of pipenv

umbral crypt
#

frustrated by pipenv or just generally better to go with a container?

native tide
#

My take is if you're using a container, you already have an isolated environment, so no need for the virtualenv

#

pipenv combines pip and virtualenv

#

you can just install the requirements directly with pip and and skip the virtualenv, but yes, you probably need to use settings as well.

calm plume
#

I typically use poetry for everything, but when in containers, I disable the creation of a venv by poetry

olive tiger
native tide
#

i want this image to come on the blank right side

native tide
#

any ideas?

autumn birch
#

Where to ask html javascript?

native tide
#

this channel? or off topic channel?

autumn birch
#
str='[(AA01, None), (AA02, P639997(3))]'```
How to turn this string to json in js?
ruby palm
#

Question about Flask

#

I notice people hardcode IPs following the pattern of having Config classes in config.py

#

Wouldn't it be better to programmatically get the IP address?

olive acorn
#

i'm looking to build a website. I've decided to use React, Next.js, and Express for it. It will be a simple site for groups to vote on polls, but also involve using locations (google API?). I'm very new to building websites and web apps so I was wondering if anyone has advice for:
1.What database and any other specific frameworks (e.g.., Express) I should use
2.what steps I could/should take from start to finish (I'm having trouble figuring out how to get started)

inland oak
#
  1. if you are going to use database, PostgreSQL database will work in average for everything backend related
#
  1. a) Yeah, probably starting from choosing technologies could be good
    b) then it would be a good place to start from "Use cases"
    writing/thinking which interacting scenarios user will have with your web site
    c) Optionally extending, use cases how they would be looking in data flow diagramms, how use cases would affect data flows in your applications with programming parts
    d) modelling which tables and relationship your database will have
    f) architecture, which servers and what's installed on them? how independent applications will interact with each other?
    e) how your web site will look like, design, user interface
    g) then planning implementation details / or just already going to coding.
#

for additional information I could recommend, System Analysis & Design 6th edition by Dennis, Wixom, Roth

dusk portal
#

@inland oak hey bro have u ever used cpanel?

dusk portal
#

ohk

inland oak
#

GUI to contorl server? urgh.

#

never going to use it, because it is against of InfrastructureAsCode principles

dusk portal
#

oh

inland oak
#

It could be fine for you, it looks like it simplifying things for regular user

#

but I chose being DevOps as second specialization, this specialization has certain philosophies to follow

ruby palm
#

Question

#

What happens if you make an HTTP request during handling of a request in a Flask route function?

#

Would the entire application pause?

inland oak
#

if you are writing Async, u have more flexibility i think (example, handle additional 100 requests at the same time instead of in sequence)
Also you could be using.... Multithreading or multiprocessing to handle the flow differently

ruby palm
#

I see :) thank you!

#

Question, how do geolocation APIs that once GET'd get you your city, etc, actually know your city?

inland oak
#

in both choices (but not in Sync), you could fire your additional request in a "Fire and forget" mode for example

#

it is inited and will be handler later or in parallel, but you already go for other stuff in your main request body

ruby palm
#

That's quite useful to know, thank you very much!

#

Bumping question: how do geolocation APIs that once GET'd get you your city, etc, actually know your city?

inland oak
#

it depends on which API you mean, but if you mean APIs that do it by IP address, then answer is...
every IP address belongs to some Internet Service Provider company, and every static IP is already accounted in each town is it located.
So.... with matching your IP address, we could point to a region or town where this IP address is used. In most cases it is enough to locate city.
So basically they have access to database where public IP addreses are registered

If we talk about Mobile Apps, then applications could be having access to your geolocating modules for more precise coordinates

ruby palm
#

Awesome! Thank you very much :))

#

Let me bring you an example

#

That api is used by this module

#

Which works like this

#
simple_geoip = SimpleGeoIP(app)


@app.route('/')
def test():
    # Retrieve geoip data for the given requester
    geoip_data = simple_geoip.get_geoip_data()

    return jsonify(data=geoip_data)
#

It returns this:

#
{
  "ip": "8.8.8.8",
  "location": {
    "country": "US",
    "region": "California",
    "city": "Mountain View",
    "lat": 37.40599,
    "lng": -122.078514,
    "postalCode": "94043",
    "timezone": "-08:00"
  }
}
inland oak
#

it is IP address locator, which i mentioed first

ruby palm
#

but if you mean APIs that do it by IP address, then answer is

#

So that'd be that type of API?

inland oak
#

they provide access to their database with their API
so you could use their data, but did not have abilities to download their database
Software as a Service (SaaS)

ruby palm
#

Awesome, how do these guys access to such database of public IPs?

inland oak
#

No idea. As first and simpliest idea, they copied from other guys who identified people

#

It is all coming, where the first person found the data about it? ๐Ÿค”

#

no idea.

ruby palm
#

Ohh, I see

#

Ok, so I make a HTTP GET to that API with their API key

#

They receive it

#

And they get my IP from my HTTP GET request

inland oak
#

I was able to find some public databases regarding it before btw

#

just a matter of googling

ruby palm
#

Now, once they get my IP, the obtained IP is public right?

#

The IP of mine that figures in the HTTP headers

inland oak
#

yes they obtain your public IP