#web-development

2 messages · Page 52 of 1

native tide
#

what no dont store the password in the session

#

thats bad

cosmic lantern
#

but why should I store the ID in the session

#

someone could just guess it

#

or look at the API which shows the user IDs

native tide
#

that way you can check if the user is logged in or not

#

you dont return the password on an API call. also your password is hashed even if they have the password its no good

cosmic lantern
#

yeah sure

native tide
#

i hope youre hashing your password

cosmic lantern
#

password is hashed

native tide
#

in the session store something like username or id that you can if needed query the DB

cosmic lantern
#

but I need some kind of token in there in order to verify if the user is authorized to view the page

#

and the user ID is publicly accessable

native tide
#

so?

cosmic lantern
#

so should the userID be the only thing in the session?

#

if so, an attacker could just look at the user id of another user, set that as their session and have access to all data of the other user

native tide
#

you can add other things as well but you also want something that can be used to query the DB

#

the only way to set the session is by loggin in

cosmic lantern
#

yeah

native tide
#

the session is set by the server not the client

cosmic lantern
#

yeah

native tide
#

even if the attacker has another users ID they cant really set the session to that ID

cosmic lantern
#

oh, is the session hashed?

native tide
#

yes there is a SECRET_KEY that you can set that is used by Flask to hash the session

cosmic lantern
#

ah, that makes sense

#

so when an attacker gets access to the DB/the file the SECRET_KEY is stored in, they'd have access to every user's data

native tide
#

yea i guess you could say that. but if the attacker can get access to the secret_key you would have bigger problems at hand

cosmic lantern
#

yeah, then they'd also have access to the DB

#

well, thanks!

static night
#

How i can login in Django admin if I created new project with PyCharm?

#

Can someone help me please?

nimble epoch
#

What relationship type does a like and dislike system use?

#

?

vagrant adder
#

@native tide hello there

#

@nimble epoch many to many

native tide
#

fellow flasker 🙏🙏

#

sup saki

vagrant adder
#

and a lot of them csgs cloud

#

sup

native tide
#

ngl this server is popping

vagrant adder
#

let's not speak off-topic here, mods like to keep to the rules

nimble epoch
#

Yeah yeah

#

And i can use many to one for a comment and post

#

Right?

vagrant adder
#

i created flask graphql api back in february, it has event-based databased design

#

like you can join and leave

#

something like likes and dislike, you can like and dislike a photo

nimble epoch
#

Okkk

vagrant adder
#

@nimble epoch it's a bit of different talk when it comes to comments

#

what if i comment on a comment

#

how would you store that

nimble epoch
#

Another comment model

#

😁

vagrant adder
#

well, that would be a database flood, really :p

#

miguel grinberg made an article about nesting comments and such

nimble epoch
#

I suckkkk😎

vagrant adder
#

i would highly reccoment to read that article, he talks about it implementing 2 algorithms/methods if you can call them that

#

sending the article right now

nimble epoch
#

Thnx

nimble epoch
#

All about these stuffs?

feral minnow
#

Guys Im trying to get a value from an option Elem

#

using flask

vagrant adder
#

@nimble epoch he talks about nesting comments, like reddit has

#

when you comment on a comment, someone comments on your comment etc

nimble epoch
#

Thats ugly

#

And a little complicated

vagrant adder
#

well, you can't really deal with it differently

feral minnow
#

It return None as fast as the options being rendered

nimble epoch
#

Im @nimble epoch 😎😈👹

vagrant adder
#

i mean you can but you would be making a query for every comment which can be very exhausing your database

feral minnow
#

Any ideas about how I can make the program wait until the user can choose his option?

native tide
#

@feral minnow what do you mean it returns none as soon as its rendered?

#

im guessing youre using flask-forms

feral minnow
#

you mean request.form?

native tide
#

no Flask-Form

feral minnow
vagrant adder
#

so you are using request.form method?

feral minnow
#

yup

#
    if request.method=="POST":
        session["link"]=request.form["link"]
        link=session["link"]
        res=requests.get(link)
        res.raise_for_status()
        soup=bs(res.text,"html.parser")

        
        Elem=soup.select("body > div.body-site > div.container.container-main > div.container-main-left > div.panel-story-chapter-list > ul  a")
        
        ChaptersName=[]
        for i in range(len(Elem)):
            href=Elem[i].get("href")
            regexName=re.compile(r'chapter_\w+\.?\w*/?')
            regexFind=regexName.search(href).group()
            fullName=regexFind.replace("/C","",1)
            fullName=fullName.replace("_"," ",1)
            ChaptersName.append(fullName)
        return render_template("manga.html",ChaptersName=ChaptersName ,link=link)
    session["start_chapter"]=request.form.get("start-chapter")
    start_chapter=session["start_chapter"]
    print(start_chapter)
          
        



    return render_template("manga.html")```
vagrant adder
#

you are doing a big bazinga here, i see

feral minnow
#

bazinga ?

vagrant adder
#
session["link"]=request.form["link"]
link=session["link"]
res=requests.get(link)
res.raise_for_status()

do you need to set up session every time?

#

if not, this can be done with 2 lines

feral minnow
#

I need it to another function

vagrant adder
#

fair enough

#

okay, so what is your problem

#

what part of html you wanna grab

feral minnow
#

the select Element

#

I want the user to choose a chapter

#

then I get this value and do things to it

#

or the program*

vagrant adder
#

i see 2 selects, which one are you targetting

feral minnow
#

both

vagrant adder
#

that's gonna be real tough

feral minnow
#

oh

vagrant adder
#

i would say take a look at flask_wtf and wtforms

#

if you rewrite that with wtforms you are gonna save yourself both time and reduce code complexity

#

if you continue to target forms with bs4, it's gonna be a big mess

nimble epoch
#

One none important quesssttioon

cosmic lantern
#

@native tide quick question, aren't sessions supposed to expire after some time? when I have a static password and a static value to encrypt, the session cookie always has the same value and therefore it won't expire. Did I miss something?

nimble epoch
#

Is like system like >>>

#

tags = db.Table('tags',
db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), primary_key=True), db.Column('page_id', db.Integer, db.ForeignKey('page.id'), primary_key=True)
)
class Page(db.Model):
id = db.Column(db.Integer, primary_key=True)
tags = db.relationship('Tag', secondary=tags, lazy='subquery',
backref=db.backref('pages', lazy=True))
class Tag(db.Model):
id = db.Column(db.Integer, primary_key=True)

#

Nut with some differences

vagrant adder
#

i already see symptoms of longlineivitis :))

#

@nimble epoch if it's pure sqlalchemy, folks over at #databases will probably know it better

feral minnow
#

@vagrant adder Im using bs4 to get something from another page then add them to options

nimble epoch
#

No its flask_sqlalchmey

vagrant adder
#

it's pretty similar

nimble epoch
#

🙏

vagrant adder
#

@feral minnow you are scraping data real time while serving site?

#

that sounds messy

#

does the site allow scraping?

feral minnow
#

I scrape it before if that what you mean?

vagrant adder
#

so you make a request to flask, flask scrapes the site and gives back the response?

#

is that the process order right now

feral minnow
#

yup

vagrant adder
#

that sounds really really messy

feral minnow
#

like illegal?

vagrant adder
#

nope, just bad practise

#

making a request while handling one can be resource intensive

feral minnow
#

so maybe the program will crash?

#

Everything is working fine for now

nimble epoch
#

Ok @vagrant adder in Comment Replies the comment model has been related to itself but ....

#

What is a remote_side?

#

The id is added to it like a list type

#

And when adding commet

#

Is it parent or parent_id?

#

Oh oh ok thats in backref

#

But what is remote_side

#

What it does?

vagrant adder
#

i think folks over in #databases can explain it, only thing i know it does is it helps with self-referential databases

nimble epoch
#

Okk thanks

vagrant adder
#

maybe this helps

nimble epoch
#

hasn’t explained

#

Its ok what im good at is surfing no worries 😉

static night
#

How i can login in Django admin if I created new project with PyCharm?

smoky skiff
#

hmmm I'm trying to use sse for loading status update for my react frontend
keep on getting this error MIME type ("application/json") that is not "text/event-stream".
this is my python code:

def publishLoadingStatus():
    sse.publish({ "percent": "10", "message": "creating user directories..."}, type="update")
    return { "status": True }
    # return flask.Response({ "status": True }, mimetype="text/event-stream")

This is react code:

componentDidMount() {
        this.eventSource.addEventListener('update', e => {
            
            this.updateLoadingScreen(JSON.parse(e.data))
        })
    }

    updateLoadingScreen(data) {
        console.log("this function is called: ")
        console.log(data);
    }
kind steppe
#

interesting

smoky skiff
#

tried the flask.Response(, mimetype=) but get a cors error, maybe my syntax is wrong? but not too sure

#

tbh.,, not sure what to put inside flask.Response() first argument

kind steppe
#

I'm going to setup a test application doing the same thing and see what I can get

smoky skiff
#

thanks, really relaly appreciate it

#

been stuck on this for awhile now...

#
this.eventSource = new EventSource('https://api.server.com/events')
        // this.updateLoadingScreen.bind(this)
    }


    componentDidMount() {
        this.eventSource.addEventListener('update', e => {
            
            this.updateLoadingScreen(JSON.parse(e.data))
        })
    }

    updateLoadingScreen(data) {
        console.log("this function is called: ")
        console.log(data);
    }
#

this is the semi-full react side code

kind steppe
#

yeah I'll just spin up the baseplate react app and put some stuff in

smoky skiff
#

my frontend and backend are bothing running https

#

i dont think that sshould matter too much tho

kind steppe
#

so @smoky skiff is this the error you get? Access to resource at 'http://localhost:5000/send' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

#

(with different domains)

#

okay so, I can get everything working locally

#

@smoky skiff make sure you are connecting the event source to the URL you pass into the bit here:

app.register_blueprint(sse, url_prefix='/stream')

#

not the one that you use to publish events, otherwise it will break

smoky skiff
#

are using flask.Response(mimetype=)?

kind steppe
#

no, that bit is irrelevant

#

because that is just for publishing events

smoky skiff
#

hmmm, i got rid of the app.register_blueprint(sse, url_prefix='/stream')

kind steppe
#

then it won't work

#

let me explain

smoky skiff
#

cuz i wasnt sure how my endpoint pointing thing worked

kind steppe
#

that code basically says 'okay, clients connect to /stream and wait for events'

#

then you have an endpoint where you call sse.publish

#

sse.publish pushes that event to all the clients who are waiting on /stream

smoky skiff
#

ahh okay

kind steppe
#

you'll need to add back the register blueprint bit

smoky skiff
#

thats very similar to webscoket stuff

#

i have another question if u dont mind

kind steppe
#

yep

#

for sure!

smoky skiff
#
# @cross_origin()
def publishLoadingStatus():
    sse.publish({ "percent": "10", "message": "creating user directories..."}, type="update")
    return { "status": True }
    # return flask.Response({ "status": True }, mimetype="text/event-stream")```
#

then in this app.route what is this doing?

#

if everything is waiting on /stream

kind steppe
#

ah so, that is just example code

#

when you visit /events in your browser, sse.publish will put an event on /stream

smoky skiff
#

oh

#

so technically i dont need this?

kind steppe
#

you do not

smoky skiff
#

app.route

#

hehehehe

#

whatta waste of time

kind steppe
#

ah well

#

you do need that to route your users

#

because somewhere in your code you need to run sse.publish

smoky skiff
#

can i just call the function?

#

def publishLoadingStatus()

#

?

kind steppe
#

you'll need to have something trigger the function but yes

smoky skiff
#

so since im doing loading screen status sort of thing

kind steppe
smoky skiff
#

im planning on exeuting this function with percentage argument

#

react will update the state with new percentage value

kind steppe
#

yeah, but something needs to trigger the function to be called on the API

smoky skiff
#

hmm trigger?

#

sorry...

#

not quite understanding that part

kind steppe
#

so something needs to run publishLoadingStatus

#

when will publishLoadingStatus know how to start running?

smoky skiff
#

that can be just ran inside the python script

#

lets say i have 5 function which are basially steps

kind steppe
#

it can, but something needs to start the functions running

smoky skiff
#

aftter each complete just execute the function

kind steppe
#

the normal way of doing it would be websockets usually or a request from react saying "okay start the loading"

#

and then flask can run functions

#

because flask is a web framework it only really will run functions when it gets a request

smoky skiff
#

ah so some sort of form submition

#

can execute the function then

kind steppe
#

yeah that could be it

smoky skiff
#

ah okay okat

#

so then i technically need the

#

app.route

kind steppe
#

because that adds an entrypoint

#

yeah

smoky skiff
#

ah okay okay cool cool

#

got an idea now

#

thanks so muchc

kind steppe
#

so that react has something to tell the API that it is there and it is ready

#

no worries

smoky skiff
#

the docs arent too great for sse

#

so i was veryt confused...

#

nnot much resource on online too

#

oh kay

#

it worked

#

@kind steppe Actually thanks so much

#

holy shit

kind steppe
#

No problem

#

If things get ridiculously complicated then there are alternate methods, either through websockets or even just AJAX polling

smoky skiff
#

Access to resource at 'https://api.domain/stream' from origin 'https://domain.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

#

didd u also get this? how did u solve it?

kind steppe
#

ahh so

smoky skiff
#

the @cross_origin?

kind steppe
#

either that or the resource specific

smoky skiff
#

i think im getting this error

#

while trying to connect to /stream

kind steppe
#

yeah

#

so maybe uh

#

one sec

smoky skiff
#

hehe i do have cors enabled tho

#
app = Flask(__name__)
app.config["REDIS_URL"] = "redis://localhost"
app.config['CORS_ORIGINS'] = ['*']
app.register_blueprint(sse, url_prefix='/stream')
#
CORS(app, support_credentials=True)
kind steppe
#

hmmm

#

well that is odd

#

try remove it

smoky skiff
#

im thinking error in my ode

kind steppe
#

just have CORS(app)

smoky skiff
#

seems like it throw this error if i have error in my code

kind steppe
#

also support credentials is a bad idea

smoky skiff
#

cuz its not able to reach the @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Headers', 'Accept,Content-Type,Origin,Authorization') response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS') response.headers.add('Access-Control-Allow-Credentials', 'true') return response

kind steppe
#

ahh actually

#

you can't have * and support_credentials

#

since that is unsafe

smoky skiff
#

ah okay

kind steppe
#

try set app.config['CORS_ORIGINS'] = ['app.domain']

#

also, you don't can remove that after request thing, this should handle it all

rustic pebble
#

If I set this: {'works':True} on python, then I send it over with http and receive it on js, will the True be a boolean so it is written as true or a string?

kind steppe
#

using what framework?

#
>>> json.dumps(True)
'true'

JSON specification means all booleans are lowercase, so I'd be surprised to see uppercase booleans

rustic pebble
#

Say I received it using fetchapi and sent it using flask

kind steppe
#

yeah, lowercase

#

flask's jsonify handles that

rustic pebble
#

Will it still be a bool?

kind steppe
#

yep, if you use JSON.parse

#

because flask will convert it to '{"myvar": true}'

rustic pebble
#

So in this case

#
def data_to_jwt(data):
    headers = {'alg': 'RS256'}
    key = read_file('./privateKey.pem')
    token = jwt.encode(headers, data, key).decode('utf-8')
    return token

def get_cookie_data():
    token = request.cookies.get('user')
    data = jwt.decode(token, read_file('publicKey.pem'))
    return data
#

if data contained a bool

#

it would act as as string?

kind steppe
#

no, it would be a bool

#

see this ```js

JSON.parse('{"myvar": true}')
{ myvar: true }

rustic pebble
#

Aha okay

#

Thanks

kind steppe
#

no problem

rustic pebble
#

😄

abstract geyser
#

Hello everyone ! I have a question about the 400 error in Django.

native tide
#

@cosmic lantern cookies do indeed expire. and you can set expiration time on flask-sessions.

uneven dragon
#

Hi

#

Just started with flask

#

Lovin it

native tide
rustic pebble
#

So using this class I am getting the following error

#
class User_Model(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    discord_id = db.Column(db.Integer)
    username = db.Column(db.String(500))
    email = db.Column(db.String(500))
    subscribed = db.Column(db.Integer)
    plan = db.String(db.Integer)
    discord_status = db.Column(db.Integer)
    profile_picture = db.Column(db.String(1500))

    def __init__(self, discord_id: int, username: str, subscribed: int, plan: int, discord_status: int, email: str,
                 profile_picture: str):
        self.discord_id = discord_id
        self.username = username
        self.subscribed = subscribed
        self.plan = plan
        self.discord_status = discord_status
        self.email = email
        self.profile_picture = profile_picture
#

TypeError: %d format: a number is required, not String

#

Full traceback

#

Any ideas on why that could happen?

#

I am not sure how to fix this

#

;D

tired root
#

@rustic pebble

#

plan = db.String(db.Integer)

#

should be

#

plan = db.Column(db.Integer)

rustic pebble
#

ah

#

Damn, I never saw that

#

Thanks a lot @tired root

tired root
#

happens to the best of us

rustic pebble
#

😄

nimble epoch
#

Again a question

#

How can i work with a many to many flask_sqlalchemy database

#

?

rigid laurel
#

Resolve it via a link table

nimble epoch
#

Like?

rigid laurel
nimble epoch
#

I meant how can i work with api

rigid laurel
#

So how to query with a many to many relationship?

nimble epoch
#

Yeah

#

That wasnt what I expected

#

Ok ok

#

I think i got it

#

Thats working

#

Thanks though man

#

Go rest

nimble epoch
#

Again a question

#

Imagine a user can like another user just once i gotta do something with my models or i gotta add conditions?

#

I cant process it🤨

dusk zodiac
#

Any selenium users here ?

rustic pebble
#

@dusk zodiac Whatsup

dusk zodiac
rustic pebble
#

From what I can hardly see you are missing the chromedriver

dusk zodiac
#

The chrome driver is there... the interpreter can load it

The executable of chrome browser is located in the path I wrote in the code, the error message says it can't locate it

lean timber
#

hi all, I'm trying to make a website checker. I can get to the website on a normal browser but when I tried wget there's a 500 internal server error.

#

oh and GET brings back well something, background image is listed as a image/png; base64 data

#

does anyone have any ideas how to alternatively query the site that might work?

#

not sure if I the normal site would return something different then an error

toxic marten
#

Which are the biggest difference between flask and django? At first i did't know which one learn, but i red some articles on internet that say if you are a beginner in backend, it's suggested to start with flask. Now im learning flask, but honestly i don't really like it, often im confused and stuck. I would try to use django, just to try it, and see if I like it more than flask. i need to talk to someone (possibly in dm) about this. 😅

#

And why flask is suggested for beginners in backend?

nimble epoch
#

Man man

#

Im stuck too

#

I have learned flask and djngo

#

But flask is easier and i think more fun

#

Flask with its extensions is great

vagrant adder
#

@toxic marten flask has "do it yourself" approach

#

you aren't given a function that magically solves 50 problems, you get to tackle the logic at lower level and therefore refining your thinkin skills

#

and django is more batteries included

#

you get almost everything in the box, less stuff to fiddle

nimble epoch
#

But i dont see any special thing with django

toxic marten
#

So flask is more customizable

#

But is more complicated flask or django?

nimble epoch
#

Django

toxic marten
#

Why?

nimble epoch
#

I have worked with both man

toxic marten
#

Can we talk in dm?

nimble epoch
#

Its not

#

But flaks is easier

#

Ok

smoky skiff
#

@kind steppe back here again.. sorry bout that.. I was wondering if theres a chance uwsgi or nginx is blocking the connection to sse?

kind steppe
smoky skiff
#

u think its nginx not uwsgi?

mighty herald
#

Hey guys I'm making a form in flask. There's a select field with the options 1 through 7. How can i make it so that depending on the users choice(1 through 7) that many string fields will be made for the next question on the form.

nimble epoch
#

Youre using flask_wtf?

mighty herald
#

yes

nimble epoch
#

Whats the problem?

#

The user selects

mighty herald
#

I'm trying to make it dynamic. For example, so that when the user selects 3... 3 stringfields are available to write 3 courses

nimble epoch
#

Ooohhh

#

No idea i myself never though about it

mighty herald
#

Okay no problem

smoky skiff
#

@kind steppe hmmm doesnt seem to fixx it

#

now getiting timeout error

#

*14 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 69.172.162.104, server: api.io-powered.app, request: "GET /stream HTTP/1.1", upstream: "uwsgi://unix:///home/jason/io-backend/main.sock", host:

#

i think it has to do with trying to connect to redis-server

feral minnow
#

Guys how I can return a value from a selector Elem using flask?

native tide
#

@mighty herald youre gonna need some JavaScript magic.

#

listen to an on change event on the options and depending on the selected value create the required amount of input fields and append to the div

feral minnow
#

Anyhelp pls

abstract geyser
#

So, I have DEBUG=True in my Django project, and I am using a ModelViewset to send serialize a model, and I am getting a 400 error when I try and post to this ModelViewset through the API. Is this a normal error, or have I done something wrong ??

native tide
crimson dune
#

I'm using latest flask and sqlalchemy. I've got an MofN relationship between Person and Event with a backref of attendance_records and I notice that when I inspect the variables I can see that person is the same as person.attendance_records[0].person and that this nests recursively all the way down, e.g. person.attendance_records[0].person.attendance_records[0].person.

Is this expected? If this scales to 100s of people and 100s of events is this going to cause a major resource hit?

distant ferry
#

is there anyone interested in jumping into a private project on github? It's a personal project whose purpose is to allow developers to get hands-on experience. The ideal candidate should have notions of how to work with git and github, and have basic knowledge of front-end technologies. Even if one does meet the requirements, please pm me should he/she be interested to know about the project.

rustic pebble
#

Does anyone know how to setup PayPal subscriptions in a flask app?

#

I am getting a hard time implementing it

#

😦

fossil mist
#

Hi everybody, I'm new with Flask and I am struck with sqlalchemy to implement an one-to-many relationship. I have a models.py file and inside it I have many models like Group and Skill (I am implementing an api for my portfolio). A group can have multiple skills. When I try to import my db object (created in int.py ) in the python shell I get an error :

sqlalchemy.exc.InvalidRequestError: When initializing mapper mapped class Group->Group, expression 'Skill' failed to locate a name ("name 'Skill' is not defined"). If this is a class name, consider adding this relationship() to the <class 'portfolio.models.Group'> class after both dependent classes have been defined.```
#

Here is my code :

#
class Group(db.Model):
    __table_args__ = {'schema': 'portfolio'}

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(255), nullable=False)
    text = db.Column(db.Text, nullable=False)
    activated = db.Column(db.Boolean, default=False)

    skills = db.relationship('Skill', backref="group")

class Skill(db.Model):
    __table_args__ = {'schema': 'portfolio'}

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(255))
    logo = db.Column(db.String(255))
    activated = db.Column(db.Boolean, default=False)

    group_id = db.Column(db.Integer, db.ForeignKey('group.id'), nullable=False)```

Can someone tell me why Group can't find the relationship? Thank you in advance.
jagged lark
#

!codeblock can you use a codeblock to format your code please? thanks!

fossil mist
#

@jagged lark Yeah, sorry

nimble epoch
#

I tried to send a message using flask_mail but it says:

#

ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine activity refused it

#

Whats the reason?

rustic pebble
#

Well

nimble epoch
#

Well?

rustic pebble
#

First of all, it is actively not activity, and second, are you sure that there are ports open to receive the email?

nimble epoch
#

Yeah yeah

rustic pebble
#

Obviously the target machine won't accept your request or is not reachable at all

nimble epoch
#

Is it related to the MAIL SERVER

#

?

#

Could be?

#

Or port or sth?

#

Yeah man it was related to MAIL SERVER configuration in the app

#

Thanks though

rustic pebble
#

Oh shoot

#

I am drawn into my flask app, I was having a huge problem setting up paypal, glad to see you fixed it @nimble epoch

nimble epoch
#

Yeahh

#

Its nice to see you glad

rustic pebble
#

😛

nimble epoch
#

😉

livid wagon
#

hey everybody. About a year ago i started a project using Django Rest Framework. Im resuming it now and trying to run it, but I cant get python manage.py runserver

I really have no idea how i set up the project last time, would really appreciate some pointers. Similar issues ive found on stackoverflow talk about virtual environments and python3 which i am sure I did not deal with before.

My current python version is 2.7.17

my manage.py looks like this:

#!/usr/bin/env python
import os
import sys

if __name__ == '__main__':
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cotizaciones.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise 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?"
        ) from exc
    execute_from_command_line(sys.argv)

dont know what other info i can give but id be happy to if someone is willing to help 🙂

#

the error i get with python manage.py runserver is:

File "manage.py", line 14
    ) from exc
         ^
SyntaxError: invalid syntax
#

i really have 0 python knowledge except for the little django rest framework backend I did a year ago

compact lion
#

raise x from y is a python 3 construct if I remember correctly

livid wagon
#

:0, so maybe i did deal with python 3

#

haha ill look into that, thanks!

compact lion
#

Yup, python 3 construct.
Python 2: raise_stmt ::= "raise" [expression ["," expression ["," expression]]]
Python 3: raise_stmt ::= "raise" [expression ["from" expression]]

rustic pebble
#

I am creating a shop right now and I want the admin to be able to generate coupons through a discord bot.

#

Supposedly the discord bot sends a request with a coupon in its body

#
@app.route('/coupon', methods=['POST'])
def create_coupon():
    data = request.json()
    if data['key'] == 'NcJ92yVJtmmYUDAACF8WMCC':
        new_coupon = data['coupon']
        with open('./coupon.txt', 'a+') as coupons:
            coupons.readlines()
            exists = False
            for coupon in coupons:
                if coupon == new_coupon:
                    exists = True
            if not exists:
                coupons.write(coupon + '\n')
                return {'coupon': new_coupon}
    return {'coupon': 'There has been a problem registering the coupon.'}

@app.route('/check')
def coupon_check():
    data = request.json()
    user_coupon = data['coupon']
    with open('./coupon.txt', 'a+') as coupons:
        coupons.readlines()
        for coupon in coupons:
            if coupon == user_coupon:
                return {'exists':True}
        return {'exists':False}
#

would the first route successfully append the coupon to the coupons text file?

#

And if yes. When I did the check in the second route, would it return {'exists':True} if it found the correct one?

#

I really don't want to do this in the wrong way

native tide
#

@rustic pebble yea your first route should work fine. couple things id change would be to read one line at time rather than read the entire file. and just return after exists= True

rustic pebble
#

I have changed it up a bit

native tide
#

👍

rustic pebble
#

Thanks for answering tho

native tide
#

no prob.

native tide
#

Of all the errors that I've gotten since I started Python, sqlalchemy.exc.IntegrityError or something along those lines is probably my least favorite one to get. Basically the reason why is that it means "shut the server down, drop the entire database, attempt to get working whatever wasn't working exactly, create the table, repopulate the table with exactly the necessary data.... It's really probably the lamest process ever.

#

Is a good solution to this getting Alembic set up so that I can just migrate changes?

#

I think Im gonna set that up before I mess around with it anymore because Im tired of that above process.

#

The main reason why this sucks so bad is that I cant just crunch out the entire database in one go.

#

I tried to do that. What it results in is not being able to identify the source of why things dont work. Because its my first time I have to develop each part of it and because SQLAlchemy is frankly such a mess... learning to do each relationship is...

#

I just have to set up migrations haha.

#

Im sure that will make it a lot better

small crest
#
<!DOCTYPE html>
<html>

<head>
    {% if title %}
        <title>Flask Blog - {{ title }}</title>
    {% else %}
        <title>Flask Blog</title>
    {% endif %}

</head>
<body>
    {% block content %}{ % endblock %}
</body>

</html>
#

I am getting this error from jinja

#

jinja2.exceptions.TemplateSyntaxError: Unexpected end of template. Jinja was looking for the following tags: 'endblock'. The innermost block that needs to be closed is 'block'.

shell garden
#

Ben Fenerbahçe’de çalışmayı çok istedim. Bundan da gurur duyuyorum. Fenerbahçe’den gitmek kolay mı? Ama kalmak da çok kolay değildi. Kulübümde kalmak için çok çalıştım. Bunun bilinmesini isterim. Ama şunu da unutmayın. Benim istifam teknik bir karardır. Ve tekrar rica ediyorum speküle etmeyin lütfen. -Ersun Yanal

nimble epoch
#

@small crest you still get the error?

small crest
#

nope

#

see the space

#

in between the { and %

nimble epoch
#

Yeah

small crest
#

that was the problem, silly me

nimble epoch
#

Happens

#

Its ok

small crest
#
<body>
    {% block content %}{ % endblock %}
                      //^ that space caused an error
</body>
#

for anybody wondering: DO NOT MAKE THIS MISTAKE

#

tips from a fellow newbie

quasi ridge
#

template languages make me cranky

#

jinja, e.g., kinda seems like it's just python. But it isn't.

drowsy rune
#

What's the error @livid wagon ?

#

anyone use firebase by any chance?

native tide
#

Hey.... I'm starting on a new web application, and have been looking into using UUID so someone with the primary key can't simply go up or down one to discover new objects. However, from what I've read, using UUIDs as primary keys seems to make queries run a bit slower.

I was thinking of some hybrid approach to get around this where its "real" primary key is still an auto-incrementing integer, while an extra web_slug attribute can hold the UUID, that is both displayed in the url, and is what is queried when a new URL is requested.

Does this sound alright, or is there a better approach? My main priority is simply removing the ability for users to discover new objects by messing with the object ID in the URL. Thanks

quasi ridge
#

I wouldn't worry about the slowness

#

I mean, try it and see

#

I will bet you won't notice

#

complexity is the root of all evil. Don't do the "hybrid approach" unless you're certain it's necessary.

native tide
#

@quasi ridge I will, thank you for your answer.

frank crater
#

What is bulma and where can it be used?

#

I saw the video on their official website which says it is a css framework

#

But I don't get it, why would you need one?

#

Isn't css itself enough for that?

#

Also, is there a web framework like django or flask anyone would suggest me?

#

I feel like I'm living on the edge

native tide
#

@frank crater I've never used Bulma before but have used Bootstrap (another CSS framework) pretty extensively. CSS frameworks to web design are 3rd party libraries to Python programming. CSS frameworks define all kinds of components and building blocks that you would otherwise have to explicitly code yourself. This can save you a lot of time. Just like with programming in Python, its much more efficient to find a library for something you need done rather than reinventing the wheel yourself and spending the time building whatever. Hope that answers your question.

frank crater
#

@native tide Thanks a lot mate! I'll try bulma for now, if I feel its not matching my needs, I'll try your suggestion; bootstrap

native tide
#

People speak pretty highly on both, depending on who you ask.

#

As for a web framework, both Flask and Django are excellent. One isn't "better" than the other, but rather are better depending on what you're trying to do.

frank crater
#

But popularity is what I am searching for

#

They aren't popular without having some tight underwears

native tide
#

Flask is small, lightweight, and its basically up to you to build all of the systems up. Django is larger but takes the "batteries included" approach so a lot of functionality is directly included (orm, authentication, etc)

#

They are both popular

#

I've used both, if you're learning either the support online for them is fantastic. Any question you have has likely already been answered on stack exchange 1-5 years ago on the top of your Google search results.

frank crater
#

@native tide Is there a tutorial series on django that you'd suggest me?

native tide
#

there is, one second

#

if I had a friend new to programming ask me this same question, I'd tell him to learn flask first. If you don't understand any of the underlying concepts of how frameworks work, its not only a lot more difficult to understand whats going on with Django, but it doesn't really give you the right perspective in choosing one over the other for a given project.

#

with Flask if you follow Corey's other tutorial, you'll see step by step how to build a little web application with a nice assortment of features, along with a good understanding of the underlying architecture

#

and then with Django, it all comes together with all of its included features

#

In this Python Flask Tutorial, we will be learning how to get started using the Flask framework. We will install the necessary packages and get a basic Hello World Application running in our browser. Let's get started...

The code for this series can be found at:
https://githu...

▶ Play video
#

all of the code is available for download in the description, so its very easy to follow along if you aren't making it alongside (which I recommend)

#

I have to go now, but I hope I helped you

frank crater
#

Sure you did! 😄

#

Thanks!

native tide
#

whats a good db to use with flask?

rigid laurel
#

Postgresql or sqlite

rustic pebble
#

Thoughts on mysql? @rigid laurel

cold horizon
#

Can you read the values of HTML forms in a flask app (not flask forms) with python? Inclusive dropdown forms with <option> tags?

native tide
#

request.form @cold horizon

cobalt oyster
#

hey guys sry if I am inturupting. But I have a small question. I was asked to submit project at
You can submit via submit50 or, if comfortable with git, by pushing to https://github.com/me50/xWaterBottlex.git

#

but when I push I get this error

native tide
#

do you have an upstream set?

cobalt oyster
#
fatal: repository 'https://github.com/me50/xWaterBottlex.git/' not found
#
remote: Repository not found.
fatal: repository 'https://github.com/me50/xWaterBottlex.git/' not found
native tide
#

make sure our commands are correct

#

its origin

#

go to github and check if the repo name is correct

cobalt oyster
#

no I accidently named it arigin I guess

#
arigin  https://github.com/me50/xWaterBottlex.git (fetch)
arigin  https://github.com/me50/xWaterBottlex.git (push)
cold horizon
#

@native tide so request.form reads the selected <option> tag? Generally its able to read these with ease? Any advantage of forms created in flask instead of html?

native tide
#

flask-forms allow for you to add validation logic very easily

#

it does CSRF validation as well

#

go with flask-form

cobalt oyster
#

so @native tide from the above it can only be that the repo url is wrong right. I mean my procedures were correct right?

cold horizon
#

Its for an offline app, used internally. So validation is not that necessary. I know html forms very well thats why im asking.

native tide
#

yea you initialized your repo, create an up stream to github and then start pushing to it

cobalt oyster
#

ok thank you.

smoky skiff
#

Hey was wondering something about SSE, once the user has connected to /stream Am i able to publish anything the frontend channel is listening to? or do i have to execute the @app.route("/somepath") everytime?

rustic pebble
#

If a website owns an ssl certificate, meaning it loads on https. If someone tries to access it by typing http://example.com will they get redirected to https://example.com?

shadow orchid
#

hwy I want to create a website

#

really basic

#

(new top py)

#

no html or CSS

#

But I know python

#

like intermediate

native tide
#

@shadow orchid I think you should at least have HTML knowledge to build a website with Python.

#

Also, does anybody know how to make a button to do something when it's clicked with Python flask?

rustic pebble
#

@native tide you need to send a request to the server

#

I usually use fetchapi and add an onclick attribute to the element

native tide
#

Mhmm

rustic pebble
#

Let me try and write an example for you

native tide
#

I think I need to find a toturial since it's hard to do it like that.

rustic pebble
#

It is not that hard

#
<button onclick='send_request();'>click me</button>
async function send_request();{
    let url = '/your_route_here';
    const response = await fetch(url, {
      method: 'POST',
      mode: 'cors',
      cache: 'no-cache',
      credentials: 'same-origin',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      redirect: 'follow',
      referrerPolicy: 'no-referrer'
      });
      return await response.json();
#

this makes a request to your route when you click the button

#

@native tide

native tide
#

This is Python?

rustic pebble
#

This is html + javascript

#

you can embed it on your html by doing

#
<script>code here</script>
native tide
#

Mhmm isn't there way to use Python to do it?

#

I've never studied Javascript.

rustic pebble
#

I don't think so

#

Maybe if you add a form and then make the button submit that form to a route

#

Example:

#
<form action='/your_route_here' method='post'>
  <button type='submit'>click me</button>
</form>
#

This would do the same as the one I sent you earlier

#

But you wouldn't be able to handle the response

native tide
#

I see

rustic pebble
#

And your page might reload on submit

#

I am not sure

native tide
#

Thank you.

rustic pebble
#

Np

static night
#

If I want to make web with flask or Django I must learn html and css or I can use bulma or bootstrap?

onyx crane
#

#Django

class Race(models.Model):
    race_name = models.CharField(max_length=50)

When i create a second model and try to migrate it, i get the error that it needs a default. I get that i guess, but i have another model where this is apparently not required for the same field type. Anyone can explain ?

lilac root
#

hey is there any way to send a post request to django from a external python script, I've tried it but I get a csrf token issue, I also tried the work around by using the decorator to disable csrf requirement for a specific function in the view, but I'm looking for a more secure of by the book method for achieving this

native tide
#

i'm doing a project where i build a website and talk about the history of html, css and Javascript

#

part of the marking guide is to use a wide range of elements . For me this is kind a vague as I'm pretty new to this. What would you guys consider to be a wide range of elements?

rigid laurel
#

I'd guess it means use of semantic tags in place of divs everywhere. e.g article, section, navbar, header

native tide
#

ah righ thanks @rigid laurel

#

another question

#

I'm soo bad at design, how do you suggest choosing a font for my subheadings?

rigid laurel
#

Just pick a font for the whole site

#

and stick with it

#

it might not look perfect

#

but it wouldn't be that bad

#

roboto is a solid choice

native tide
#

ty !

native tide
#

why is css so hard?

#

and html

#

i breeze through C and Networks but this is just whack

native tide
#

It's just nothing like those things. If you do it enough you can get better at it.

#

Also, I found a way around my problem of repeatedly needing to drop my database and add new users every time I make small adjustments during design (problem i complained about the other day)

#
from shellmancer.models import *
from faker import Faker

def populate_test_users(db, num):
    fake = Faker()
    for i in range(num):
        if i == 0:
            user = UserAccount(email="admin@admin.com", password="password", is_admin=True)
        else:
            user = UserAccount(email=fake.email(), password=fake.password(), agree_over_18=fake.boolean())
        db.session.add(user)
        db.session.commit()

def drop_create(db):
    db.drop_all()
    db.create_all()

Highly recomend.

#

I wouldnt normally use star imports but its only purpose is doing testing with my models so it makes sense here imo

abstract geyser
#

I am having an error with Django Rest Framework, and it's a problem I was sure I fixed. Here is the error.

#

Could not resolve URL for hyperlinked relationship using view name "blog-detail".

#

But here is my code -->

#

serializers.py

#

`class BlogSerializer(serializers.HyperlinkedModelSerializer):

class Meta:

    model = Blog
    fields = ['blogger', 'date_added', 'blog_name',
              'blog_post', 'blog_picture_context', 'url']

    extra_kwargs = {
        'url': {
            'lookup_field': 'blog_name'
        }
    }`
#

views.py

#

`@method_decorator(ensure_csrf_cookie, name='dispatch')
class BlogViewset(viewsets.ModelViewSet):

queryset = Blog.objects.all()
serializer_class = BlogSerializer
lookup_field = 'blog_name'

def get_serializer_context(self):
    return {'request': None}`
#

I should not be getting this error, but it literally just appeared back in the stack trace.

abstract geyser
#

I fixed this error, and I have a Gist for anyone who may have come across this.

gaunt walrus
#

hi guys , i wont to install mysqlclient in python but it return error can help me

elfin mountain
#

@gaunt walrus Can you post the errors?

gaunt walrus
#

yes

lavish prismBOT
#

Hey @gaunt walrus!

It looks like you tried to attach file type(s) that we do not allow (.txt). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .m4v, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg, .md.

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

gaunt walrus
#

Collecting mysqlclient
Using cached mysqlclient-1.4.6.tar.gz (85 kB)
Installing collected packages: mysqlclient
Running setup.py install for mysqlclient ... error
ERROR: Command errored out with exit status 1:
command: 'c:\users\user\appdata\local\programs\python\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\user\AppData\Local\Temp\pip-install-4k6sbmbl\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\user\AppData\Local\Temp\pip-install-4k6sbmbl\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\user\AppData\Local\Temp\pip-record-0d3bwbam\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\user\appdata\local\programs\python\python38-32\Include\mysqlclient'

elfin mountain
#

@static night You will need to use HTML and CSS. You will use Bootstrap in your html docs. There is a Flask-Bootstrap that can extension that can help, if you choose Flask.

gaunt walrus
#

i using django

elfin mountain
#

@gaunt walrus Have you upgraded pip and setup tools in your environment?

gaunt walrus
#

pip 20.0.2 from c:\users\user\appdata\local\programs\python\python38-32\lib\site-packages\pip (python 3.8)

#

@elfin mountain yes

elfin mountain
#

Download the wheel file and install.

gaunt walrus
#

@elfin mountain ok thankyou so much

fossil mist
#

Can someone help me?

wraith sentinel
#

how to use servlets witth mysql data base without IDE??

cunning prairie
#

Hi, do you know why Django still renders admin templates from django.contrib.auth for builtin view after I set up my template dir via TEMPLATES['DIRS'] settings.py?

misty goblet
#

What is a good library to use to create a REST api?

small crest
#

what is better to learn Django or Flask
also which is better to make an online chat application'
@ me if u have answer, cause I am stumped on what to do

misty goblet
#

you can use Django with Flask

#

in fact I believe you use it by default

#

@small crest

elfin mountain
#

@misty goblet What do you mean you can use Django with Flask? They are two separate web frameworks.

#

@small crest Don't worry so much about which one, just pick one and start learning. There is no better or worse for making a chat application.

misty goblet
#

I am just going to find the door :( (I got something mixed up there)

feral minnow
#

Guys anyone know how to return a value from a flask Selectfield form?

feral minnow
#

nevermind

#

I got it

#

I used form.choice.data

#

after 3 days of searching and asking people lol...Thanks @native tide

native tide
#

Hey so this is a pretty broad question, but Django or Flask?
Let me give more context. I'm a web developer with a workable competency in python, though I'm no pythonista. I currently have a node/express project that I'd like to port to Python. I've tried Django before, and found it to be great when I needed to do something it allowed, but it was a pain to configure and work around when I needed something more custom. I also really like it's admin panel, built in auth, and how it interacts with SQL. I don't know any flask, and while I typically prefer flexibility, this project I'm working on is fairly serious and I need to make sure things are done correctly, especially auth.

queen bough
#

Django IMO. Flask is a BYO (build-it-yourself) in my experience. Django has everything there already.

#

Though it is more restrictive.

native tide
#

Yeah, that was my issue with it before. It just seemed really restrictive, and it seemed like I was constantly trying to find some workaround to do something that wasn't strictly within it's paradigm, and that was a pain. I'm just not sure if rolling out my own ORD, Auth, and Admin GUI (if I even do) would be less painful than dealing with Django's restrictions.

queen bough
#

I doubt it.

#

The admin is one of the most powerful features of Django - literally 20 lines of code and you've got a frontend to your DB.

#

Not sure if there is even a contender let alone an equivalent in Flask.

#

I haven't used it enough to know, to be fair.

native tide
#

I mean I'm sure there are pip libraries. I don't know for a fact since I haven't tried, but in express there are npm libraries that help me set up a DB fairly quickly in what is otherwise a minimalistic framework. Definitely still isn't as convenient as Django is though.

queen bough
#

Django also has amazing TDD support.

#

If that's the way you want to go.

#

Whereas with Flask you'd be managing the tests fully yourself.

native tide
#

That's actually very true, I forgot about that

queen bough
#

@native tide I've used it for many projects, always wonderful to work with. I've never personally felt restricted by the framework though, granted, I've not made a "proper" project in it yet (working on one right now).

native tide
#

That's good to know, thank you. I'll probably go with it to be honest.

queen bough
#

No problem. Flask is a really cool framework which I've enjoyed dabbling in, but I can't see myself writing a full project in it, though it has been done.

rustic pebble
#

Anyone have any ideas on why a cookie gets disappears after redirect?

agile folio
#

The whole Flask / Django argumentation: Two different projects with totally different goals, Django is more of a "batteries included" framework, Flask is more like "Batteries? Make your own batteries"

#

This makes Flask much more flexible, but also requires a great deal of development time to produce the same results as 30 lines of Django code could do.

#

It (Flask) also makes no (or very few) assumptions and is quite the opposite of Django's more pragmatic "one best way" philosophy in terms of ORM, frontend frameworks and the likes

native root
#

@rustic pebble Depends on the redirect and how the cookie was set. when you set a cookie ti comes with a "scope" that's by default only the current url it's set on and any suburls, so that's probably what you're running into

native tide
#

yeah, for some reason, newbs (myself included) often come at Django/Flask with the idea that Django is harder. If anything its exactly the opposite.

#

I love certain features of Django so much that I lament not being able to have them every second that I use Flask. At the same time, Flask has taught me more about backend procedure. I think that nothing short of learning to use both of them makes sense after using both of them. Both teach me different lessons and bring different things to the table.

#

So I think if you're in a position of deciding which to use, it doesn't matter. Pick one. When you're ready, start the other.

#

I think if either or is your first web framework, there is no way thta someone explaining the difference to you will make any sense. thats why everytime someone tries, newbs come away with the wrong impression of what the differences are. At least thats my experience.

forest aurora
#

Hey guys

native tide
#

Hello

forest aurora
#

Can I ask some advice?

native tide
#

Do it. (I might not have answers but someone might)

forest aurora
#

Okay, thanks. I’ve been feeling conflicted about my thought process regarding some code. So in my teams project, we have leaflet map markers with only one category: cities. So I am thinking to use the default marker image and stick with that. If we had other categories like entertainment, weather, transit, etc, there would be other marker images. But we don’t. So I am hardcoding it to use one image only and the team lead is against it. He says it’s good coding practice to make the image field generic enough to where if we want to change the image (for different cities or categories), we can. Having that option goes against the integrity of the blueprint. I don’t see a use for having different image for each city marker (it’s tacky) and we don’t even have other categories. I feel he is making new rules along the way. Is it bad coding practice to make the image field constant if there is no plan to have it change?

native tide
#

It is generally bad practice to hard code anything, but it's also poor design to spend extra time making room for features that you arent going to use. At the same time, if your project lead things that you will need something, maybe he has plans down the road that you dont know about? Arguments get made for both approaches all the time and both have valid points. It depends on the circumstances.

forest aurora
#

Well he calls it hardcoding but it’s just using one basic image path in the JavaScript and that’s it. We wouldn’t manipulate it in the dictionary. He’s the team lead for a class project so the project will be done when the class is. There are no further features or versions of the app.

#

I just feel it’s unnecessary if it’s not usable

native tide
#

Ah, yeah thats a weird situation. At first I thought you were arguing with your boss for no reason and was going to tell you, "Maybe dont do that" haha

#

But in this case yeah...

#

Spending time on features that arent going to be used is a waste of time

forest aurora
#

Definitely 👍 and yeah wouldn’t argue with my boss at all 😂. Thanks!

native tide
#

Maybe you should cite the concept of agile development to the person you're working with as your reasoning

#

@forest aurora say that you understand why that would make sense if there were plans to do that because it would save time, but... also point out that spending time on features that arent being used is a waste of money

#

Of course in classroom settings

#

There is always the argument, "we are doing this to learn how to do it"

#

which is also valid...

forest aurora
#

That’s perfect reasoning. We learned about that this semester. The class is called introduction to software methodology. At the moment though, I just said “gotcha” and ended the argument. If asks why I didn’t do it, then I’ll explain. I think his ego is hurt and he is trying win in any way by making new rules or calling anything illogical “good coding practice.” @native tide

native tide
#

I think a regular thing you will encounter in the world of programming is trying to get people who are very rigid about things being done a certain way seeing when its not best to do it that way.

#

Personally its a thing I have to struggle with myself sometimes.

#

Its good to be aware of it as a programmer I think.

forest aurora
#

It’s definitely new territory and I gave myself high BP with his circular reasoning so that’s why just succumbed and ended the argument prematurely. I just don’t want to waste time on useless features just because I’m told to do so by the self-proclaimed team lead. I even told our professor about it and he said he’ll have individual phone calls with us since his rigidness, disrespect, along with superiority complex has been going on since the start.

native tide
#

Yeah, people like that typically do not do well being in charge. Its a common problem in classrooms because the best person for the job doesnt always get the job, because so often it goes to whoever is most likely to say, "I am the leader" and thats all it takes.

#

I actually didnt do programming in school.

#

But I remember that problem at school

forest aurora
#

I totally agree. My professor told me not to worry as my grade will not be affected by the lead’s evaluation.

#

How many years have you been coding professionally?

#

I didn’t realize before coming into the field that there are so many non-programming skills that are extremely essential to understand

native tide
#

Yeeeah, they say that the days of the asocial hacker who never leaves his room and relies on some business guy to make everything work financially are over.

#

lol

forest aurora
#

Haha definitely 💯 totally agree 👍

native tide
#

Now if only the days of the business guy who relies on programmers to do all his work would be over 😛

forest aurora
#

We’d become obsolete and jobless! Gotta keep them dependent 😂

rustic pebble
#

@forest aurora You can create a dictionary that holds values category icon_url and then a function that builds the categories by taking input from the dictionary

#

That would mean that you would be able to add as many categories as you'd like without actually having to recode the same thing

forest aurora
#

Yeah I have the idea. Just that we have one category for the plan.

#

@rustic pebble

rustic pebble
#

Are you making this on flask?

forest aurora
#

No

rustic pebble
#

React?

#

Well, actually whatever you use you should always consider CI(continuous integration)

forest aurora
#

Django framework

rustic pebble
#

Which means making things easier and more agile to changes

forest aurora
#

Yes I think that is the next step in the process

#

Along with unit testing

rustic pebble
#

Yea unit testing is pretty important although I usually hack my way through it by testing each different component individually

#

This is where React is good at as you build each element as an individual class or function

forest aurora
#

Would need to definitely learn that library

#

Heard it’s very useful

#

Plus easier than other stuff to learn

rustic pebble
#

React is okay but you will get a hard time setting it up if you are not using an IDE. afaik PyCharm has built-in support for it, but for projects that involve react I use a WebStorm which is a similar IDE to PyCharm

#

If you want to go easy first and learn other the harder stuff later you should consider checking Vue.js

dry cobalt
#

I am decent at react if you need pointers

rustic pebble
#

Nice!

forest aurora
#

Ayyy thanks guys for tips and resources... will be sure to try to IDE and look into the github... appreciate it @rustic pebble @dry cobalt

rustic pebble
#

Sure thing

forest aurora
#

I use PyCharm currently so should be a good transition

dry cobalt
#

bro no use vscodium

#

brew install vs code

forest aurora
#

You have a Mac? Me too. I use vscode and vs for work atm

#

They have a MS full stack and prefer to use everything Microsoft

rustic pebble
#

Doesn't really matter, your websites are going to end up in a linux container after all haha

#

😛

forest aurora
#

Lol true. I should get bootcamp for windows to try out the experience. Last time I tried it, it didn’t work and my computer never got its partition back

rustic pebble
#

I'd rather use VMware

forest aurora
#

I have that too but stuff is slower on there like building apps and stuff. That’s what I’ve heard.

rustic pebble
#

Well it depends on the app you are making

#

If you are developing on C# then windows is a must

#

Same goes for Swift

#

Mac is a must

forest aurora
#

Yeah my boss found some workaround for my Mac because he thinks VMware won’t be a fuller performance but my bootcamp never returned my partition so idk

rustic pebble
#

Personally I believe a webapp nowadays should consist of the following. Backend bone in whatever language you want, Node + Docker is very good, web interface build on the framework of your choice, native windows app through C#, native mac app through Swift

forest aurora
#

I haven’t used docker but wanna try it

rustic pebble
#

That is how I perceive fullstack nowadays. In our days almost anyone can pick up flask + markup and call themselves fullstack. That is not the case anymore

#

Well here is the essence of docker:
Person 1: Yo the website doesn't work..
Person 2: Hmmm, it works on my pc
DOCKER

forest aurora
#

Because p2 is accessing through the container?

#

Do you like ssh into it?

rustic pebble
#

Well once you deploy it you are going to need to ssh in order to use it

#

But docker is as simple as running a shell script

forest aurora
#

I see. Sounds cool. I’m really interested now. I just used AWS and I really liked that 👍.

rustic pebble
#

I am building a metaengine for a game now and I will be using Kubernetes which is a docker framework in order to handle many requests almost at the same time

#

Yeah AWS is awesome

forest aurora
#

Niceee and yes it’s AWeSome

rustic pebble
#

Make sure to check out AWS Lambda, I have used it in a few projects and it provides you with a stateless-ultrafast response environment

forest aurora
#

I will for sure. Thanks for all the tips and insight. I feel like I could learn a lot from you.

rustic pebble
#

Haha, sure! Thanks

rustic pebble
#

oof

vale cove
#

Hi ! I'm new to Python ! Can we make website or game using Python 3 ( or in PyCharm maybe....) ?? Sorry for Stupid question, I just want to know orientation .....

Thanks

native tide
#

I'm I'm trying to push a boilerplate app to heroku to learn heroku...

#

I'm getting caught up here

#
remote:        ERROR: Could not find a version that satisfies the requirement pkg-resources==0.0.0 (from -r /tmp/build_efcd190cbdfc460c757ff45a1a85ce9b/requirements.txt (line 7)) (from versions: none)
remote:        ERROR: No matching distribution found for pkg-resources==0.0.0 (from -r /tmp/build_efcd190cbdfc460c757ff45a1a85ce9b/requirements.txt (line 7))
remote:  !     Push rejected, failed to compile Python app.
remote: 
remote:  !     Push failed
remote: Verifying deploy...
remote: 
remote: !       Push rejected to virucount-stage.
remote: 
To heroku.com:virucount-stage.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@heroku.com:virucount-stage.git'
(env) virufac@box:~/Projects/flask-by-example$ cat requirements.txt
click==7.1.1
Flask==1.1.2
gunicorn==20.0.4
itsdangerous==1.1.0
Jinja2==2.11.1
MarkupSafe==1.1.1
pkg-resources==0.0.0
Werkzeug==1.0.1
#

What is that pkg-resources about and why would it think it needs 0.0.0

#

I'm just gonna remove it

native tide
#

@vale cove you can make webservers that serve static web pages with python and we can make games with python with something like pyGame

vale cove
#

okie

light oracle
#

Is it hard to learn django or flask? I have done other style projects, and I know to do web development for static webpages. But now I am in a project where I would need to do login and third-party's login (like steam, instagram). Should I go with one of this two options, or do it with passports.js and node? My biggest concern is security

quasi ridge
#

I'd look for the most complete 3rd-party solution you can find

rustic pebble
#

@light oracle These 3d parties use OAuth2 which you can setup in 10 lines 🙂

#

Login with Facebook Login with Instagram Login with discord Login with gmail Login with Apple are all the same in the way you setup them up backend-wise

#

They all use OAuth2 protocol

light oracle
#

Soo in these sense, they are the same. Still I don't know which one to choose

#

I have done many things with python (user-interface, web scraiping, discord bots, and scraping) but never done dynamic webs. It looks to me, that node is better or at least more used and easy acces to learn

native tide
#

Is it absolutely necessary to go through this every time

$ git push stage master
Counting objects: 3, done.
Delta compression using up to 12 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 312 bytes | 312.00 KiB/s, done.
Total 3 (delta 2), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote: 
remote: -----> Python app detected
remote:  !     Python has released a security update! Please consider upgrading to python-3.8.2
remote:        Learn More: https://devcenter.heroku.com/articles/python-runtimes
remote: -----> Installing SQLite3
#

Like that is just the process getting started. It seems like I already installed all that stuff, doing it every time I push seems weird

native tide
#
2020-04-07T16:29:03.796450+00:00 app[web.1]: SECRET_KEY = os.environ['SECRET_KEY']
2020-04-07T16:29:03.796450+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/os.py", line 675, in __getitem__
2020-04-07T16:29:03.796450+00:00 app[web.1]: raise KeyError(key) from None
2020-04-07T16:29:03.796451+00:00 app[web.1]: KeyError: 'SECRET_KEY'

How do I set environment variable on heroku?

#

heroku config:set SECRET_KEY=$SECRET_KEY --app appname lets try this

#

et work

#

I dont know why I ask questions in chat that I proceed to immediately answer myself.

lone galleon
#

hi i try to run this function in flask with "input" display in html (like a terminal but with a simple function) no success 😦 def monprog(): while True: command = input('> ') if command == 'hello': print('hi') elif command == 'exit': exit() else: print(command)

native tide
#

So, the user has no access to the terminal on the server... So you can't do terminal based input from a flask app because its running on a server somewhere removed from the user who only sees an HTML page served to them. You have to somehow display the form as HTML and then have it submit the input as a POST request to the flask app.

#

I use WTForms which makes it pretty simple.

#

Or am i missing something maybe?

lone galleon
#

yes i think that's it. My explanation was not very clear but I will try that

supple loom
#

I am learning how to use git bash ...committing a new branch gives error untracked files present...how to tackle that?

native tide
#

try git add . which should track all files in the current directory. If you have files you don't want git to deal with, add them to .gitignore file so that you can continue to just add everything your directory without worrying about it.

#

if you have multiple directories to add git add * might be better

#

Pretty much every time you make a change you have to add those files to that list before commiting

#

Otherwise there is nothing to commit. If there are things going on in the directory that git isnt sure about when you try to commit it will tell you so that there arent inconsistencies going on

supple loom
#

I did git add

#

And it shows the file in git status

#

Says untracked

native tide
#

Hrm

supple loom
#

Okay wait

#

Solved

#

I wasn't adding before

#

Sorry

native tide
#

Its cool, its usually something like that.

supple loom
#

Gotcha👍👍

#

One thing

#

After the merge command we have to approve commit from git hub?

#

Can't be done using git bash?

native tide
#

To be honest, I dont have a lot of experience merging pull requests. Ive done it maybe one time ever. I just pull down and push up haha. Im sure you can.

supple loom
#

See i ran the merge command and there is a new pull request shows up in git hub...but it's not commited yet so i have to create new pull request from git hub and merge

rustic pebble
#

Hi, I am having a problem installing an SSL certificate in a Flask APP

#

Basically I am getting the following

#
[Tue Apr 07 18:34:21.505950 2020] [ssl:emerg] [pid 31437] AH02562: Failed to configure certificate ip-172-31-37-206.us-east-2.compute.internal:443:0 (with chain), check /etc/pki/tls/certs/server.crt
[Tue Apr 07 18:34:21.505982 2020] [ssl:emerg] [pid 31437] SSL Library Error: error:0906D06C:PEM routines:PEM_read_bio:no start line (Expecting: TRUSTED CERTIFICATE) -- Bad file contents or format - or even just a forgotten SSLCertificateKeyFile?
[Tue Apr 07 18:34:21.505991 2020] [ssl:emerg] [pid 31437] SSL Library Error: error:140DC009:SSL routines:SSL_CTX_use_certificate_chain_file:PEM lib
AH00016: Configuration Failed
#
2020-04-07 18:32:29,721 INFO spawned: 'httpd' with pid 31280
2020-04-07 18:32:29,784 INFO exited: httpd (exit status 1; not expected)
2020-04-07 18:32:32,472 INFO spawned: 'httpd' with pid 31288
2020-04-07 18:32:32,523 INFO exited: httpd (exit status 1; not expected)
2020-04-07 18:32:35,965 INFO spawned: 'httpd' with pid 31309
2020-04-07 18:32:36,016 INFO exited: httpd (exit status 1; not expected)
2020-04-07 18:32:37,018 INFO gave up: httpd entered FATAL state, too many start retries too quickly
2020-04-07 18:34:15,298 INFO spawned: 'httpd' with pid 31401
2020-04-07 18:34:15,351 INFO exited: httpd (exit status 1; not expected)
2020-04-07 18:34:16,356 INFO spawned: 'httpd' with pid 31429
2020-04-07 18:34:16,407 INFO exited: httpd (exit status 1; not expected)
2020-04-07 18:34:18,411 INFO spawned: 'httpd' with pid 31433
2020-04-07 18:34:18,461 INFO exited: httpd (exit status 1; not expected)
2020-04-07 18:34:21,466 INFO spawned: 'httpd' with pid 31437
2020-04-07 18:34:21,518 INFO exited: httpd (exit status 1; not expected)
2020-04-07 18:34:22,519 INFO gave up: httpd entered FATAL state, too many start retries too quickly

#

Both of these blocks happen many times

#

I am really not sure what I have done wrong

native tide
#

I also have a slight problem.
This is the example of setting up alembic that Im using.
https://realpython.com/flask-by-example-part-2-postgres-sqlalchemy-and-alembic/
It makes a foot note that its using flask_script, which is no longer needed because there is now a CLI built into Flask.
But for the purposes of the above example, can I just remove everything related to flask_script?

import os
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand

from app import app, db


app.config.from_object(os.environ['APP_SETTINGS'])

migrate = Migrate(app, db)
manager = Manager(app)

manager.add_command('db', MigrateCommand)


if __name__ == '__main__':
    manager.run()

This tutorial shows you how to process text and then setup a task queue with Flask. In part two, we'll set up our PostgreSQL database along with SQLAlchemy and Alembic to handle migrations.

rustic pebble
#

@native tide Yes you can

#

Actually, they way you are using it

#

It might not be possible

native tide
#

Well I just copied that from the article. It specifies that its using an old way of doing it

rustic pebble
#

🤷‍♂️

native tide
#

I kind of just wonder what the new way is

#

I'm so excited to have migrations set up

#
wordcount_dev=# \dt
              List of relations
 Schema |      Name       | Type  |  Owner   
--------+-----------------+-------+----------
 public | alembic_version | table | postgres
 public | results         | table | postgres

Pretty cool. Looks like it will work exactly like Django now. Im excited.

marsh ginkgo
#

Anyone experienced with Django?

rigid laurel
#

yes - if you have a question, just ask it

humble crest
reef canopy
#

Hello
I am trying to turn a python script into a web service
I would consider my knowledge in general python intermediate
but I have no clue how to transform it thoo
This .py file I intend to deploy as REST api
doesn't intervene with a database
it just takes in a server IP and a zip of textual files I intend to preprocess to extract content and metadata

#

anyone could help please

rigid laurel
#

Flask is probably what you want to be looking at

reef canopy
#

what about django ?

rigid laurel
#

Django is more oriented around CRUD apps than Flask is

#

and as you don't need a database

#

I don't think its a great fit

#

although it probably would work

reef canopy
#

exaactly , ùaybe DRF

#

?

#

actually I intend to store the extracted features

rigid laurel
#

DRF would work yes - but you're getting a lot of features you don't need to use

reef canopy
#

such as ?

rigid laurel
#

the ORM

#

a more complex routing system

reef canopy
#

thank you

hardy silo
#

hi all, i need help with Django. I'm doing some tutorials and I'm stuck at the start of tutorials. I don't what I did wrong but I keep getting errors even though I checked and it's same as tutorials code. Anybody?

#

quite a noob to add on this

#

is this even the right channel to ask for help?

queen bough
#

@hardy silo Yes, this is the correct channel.

hardy silo
#

I did find the answer. I was doing creating ForeignKey to another class/table and, even though tutorials didn't use this, I googled and found out that I should add on_delete=models.CASCADE

#

what is this code?

#

how come tutorials didn't apply it? django updated this?

hardy silo
#

I'm in process of getting along with stackoverflow, sry for bothering you with this

queen bough
#

No problem. Any confusions/questions?

hardy silo
#

one question, probably not that smart one

queen bough
#

No such thing as a bad question.

hardy silo
#

if I use SET(...) instead of CASCADE - for example if I delete post "message" and I want to keep that post, i can use SET to set default "message? for example: "this post was deleted because of reasons"?

#

hosts

#

I believe I saw some options in cpanel for this https stuff, when you install certificate. i used Let's encrypt, it's free

#

try

feral minnow
#

What are you trying to do?

hardy silo
queen bough
#

if I use SET(...) instead of CASCADE - for example if I delete post "message" and I want to keep that post, i can use SET to set default "message? for example: "this post was deleted because of reasons"?
@hardy silo Sorry, missed the message. It's definitely possible to keep the post, but most likely you won't have to do the queries as Django will do it for you, if that's what you mean.

hardy silo
#

Good answer for me, i think i understand now. One more thing i have to do, try it myself. Tnx 😉

queen bough
#

@hardy silo Sorry I couldn't answer in more detail - quite difficult without understanding the components being worked with.

hardy silo
#

No need to apologize. You were quite helpfull. I'm at the beggining of tutorials, long way to go.

heavy ibex
#

Hey I'm watching this video https://youtu.be/3fDy_CKO-hI and for some reason the code doesnt work for me, it's being buggy

Thanks for watching! If you enjoyed the video please be sure to like and subscribe for more videos. Have any ideas for me to make a video on? Let me know and I will most likely make a video on it!

Video Resources:
Visual Studio Code - https://code.visualstudio.com/download

...

▶ Play video
quasi ridge
#

I'm not going to watch a video and transcribe code from it to help you.

#

paste the code here, or get someone else to help

feral minnow
#

@heavy ibex Please put the code here so we can see what is the problem

native tide
#

I'm having trouble with migrating my database on heroku. It works on the local server but on the staging server it doesnt.

I'm sorry if this is a lot of info, I just dont know what it could be that would lead to answer.

(venv) virufac@box:~/Projects/shell_hacker_game$ heroku run python manage.py db upgrade --remote stage                           
 ›   Warning: heroku update available from 7.39.0 to 7.39.2.
Running python manage.py db upgrade on ⬢ sdfdsafdsafs... up, run.9750 (Free)
INFO  [alembic.runtime.migration] Context impl PostgresqlImpl.
INFO  [alembic.runtime.migration] Will assume transactional DDL.
(venv) virufac@box:~/Projects/shell_hacker_game$ heroku psql --remote stage                               
 ›   Warning: heroku update available from 7.39.0 to 7.39.2.
--> Connecting to postgresql-clear-asdfdasfdsafdsafdsaf
psql (10.12 (Ubuntu 10.12-0ubuntu0.18.04.1), server 12.2 (Ubuntu 12.2-2.pgdg16.04+1))
Type "help" for help.

dsfdasfds::DATABASE=> \d
                 List of relations
 Schema |      Name       | Type  |     Owner      
--------+-----------------+-------+----------------
 public | alembic_version | table | nbwcmytpvtdpir
(1 row)

You can see here that after migrating there arent any changes. In fact, the only reason this doesnt error saying that it cant find the empty migrations/versions/ directory is because I touch migrations/versions/.somefile to make git track it and upload.

#

When I check the logs to see what causes the error when I attempt to use the database

stagemancer::DATABASE=> \q
(venv) virufac@box:~/Projects/shell_hacker_game$ heroku logs --tail --remote stage
2020-04-08T00:44:54.821422+00:00 app[web.1]: sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "user" does not exist
2020-04-08T00:44:54.821423+00:00 app[web.1]: LINE 2: FROM "user"

This shows that the models are not being migrated.

But over here on the dev server everything runs fine

shellmancer_dev=# \d
List of relations
Schema |                  Name                  |   Type   |  Owner   
--------+----------------------------------------+----------+----------
public | alembic_version                        | table    | postgres
public | campaign                               | table    | postgres
public | campaign_campaign_id_seq               | sequence | postgres
public | character_sheet                        | table    | postgres
public | character_sheet_character_sheet_id_seq | sequence | postgres
public | gamemaster                             | table    | postgres
public | player                                 | table    | postgres
public | user                                   | table    | postgres
public | user_id_seq                            | sequence | postgres
#

You might be interested in this

(venv) virufac@box:~/Projects/shell_hacker_game$ heroku config --remote stage
›   Warning: heroku update available from 7.39.0 to 7.39.2.
=== stagemancer Config Vars
APP_SETTINGS: config.StagingConfig
DATABASE_URI: sqlite:///test3.db
DATABASE_URL: postgres://sdafadsfdsafdsafdsaf:sadfdasfdsafdsafdasfdsafdsafdsafdasfds@sdafdasfdsfdsafdsadsa.amazonaws.com:5432/dsdafdsafdsafdsafdsafdsa
SECRET_KEY: dsfdsafdsafadsfdsa

Note that, having the DATABASE_URI: sqlite:///test3.db is a mistake. I dont know how to remove that. The app isnt using it.
Also note that everything sensitive has been (hopefully) replaced with dsfsafsdaf

What is going on?

lilac root
#

I'm working on a djnago based web site and I wanted to implement a autocomplete feature in a textbox. After some searching I found that I should either data list of possible string in a JS list of I should use tries. I wanted to know how to implement this from a django perspective

native tide
#

I figured out the answers to my problem. All it took was dropping my database and starting over.

TBH, I am fearful of the day when simply dropping the database and starting over is not an option. That's how I fix so many problems.

#

@lilac root you pu the the JS to do it in your static directory and load it up in your template and run it.

#

Django is for backend. It can display the form. It can send the contents of the form to the server. It can render something on the server based on that and send it back to the user.

#

But if what you want is some interface quality of life feature in the browser, your only answer is JS

#

or often CSS but not in this case

#

Think about it this way...

#

If you want something to happen on the page that doesnt involve moving to another page or redirecting to display the changes, you need CSS or JS. IMO you would preferably use CSS for anything that CSS can do, and JS for anything it cant

native tide
#

I hope it works

vagrant adder
#

Use nginx rather

native tide
#

The limitation is working through heroku.

#

As far as I know, the only way to do it is at that application layer

feral minnow
#

Guys I want to create something which let the user download something . So If he did he will not be able to download another thing for an hour...I can do this with flask?

native tide
#

Yeah you could do that. If you wanted to do it without forcing them to make an account, you'd probably do it by IP (which they could get around just by tunneling, but it takes a smart user to do that). You could make it even more difficult by forcing them to make an account, but thats up to you.

I'd probably search to see what methods people are using to get the best results, but yeah flask can do that

feral minnow
#

oh ok I don't think i will create a login page because the goal of the website is just to let the user to download his thing then he can leave

tired root
#

@feral minnow Restricting the functionality of your site to make people pay up is a stupid idea

feral minnow
#

hm

#

Which idea you mean?

tired root
#

let's not pretend

#

this isn't my first day

#

It sounds a lot like one of those shitty share sites where you have to pay to get more downloads once you have downloaded something or get a stupid restriction which you can remove with your credit card

#

If the functionality of your site is downloads, then don't restrict

#

make the user stay

modest dirge
#

so i embedded a forum on a github page but the forum doenst show

feral minnow
#

nope and nope and nope... I didn't say something about I want the user to pay anything

#

And I will not do it

tired root
#

Then what is the goal of restricting a download to once an hour?

feral minnow
#

who will pay for something that a lot of other website offer

#

Its to control the downloading thing

native tide
#

I think if you have limited bandwidth it makes sense.... Like if its your little app that will get shut down if people are using it a lot.

Otherwise I agree with scorch

tired root
#

Eh, traffic is not expensive

#

I don't see the point of it

#

My VPS costs 2.98€ if I wouldn't get it for free and it includes 20 TB

#

so, why annoy a user with a restriction when it's so cheap?

feral minnow
#

its for the other website you can say

#

if I sent to much requests to it

native tide
#

Your VPS costs how much? Where do you have this at?

#

the VPS I have seen are pretty expensive. I havent exactly shopped around

#

But I definitely have looked at the plans and thought "Wish I had money for that"

feral minnow
#

where you host your app??!

tired root
#

@native tide There are options out there, but this a really small one with 1 vCore and 2gb ram

#

I only use it as a jump server for home office

feral minnow
#

so its not good

tired root
#

my point was the traffic though, not its computing prowess

feral minnow
#

I think i have to do the 1hour thing

native tide
#

I might have to look into that. I like the idea of having one a lot

tired root
#

@native tide 1 vCore, 2 GB RAm, 20GB NVME SSD, 20TB Traffic and 0.0004 / h computing

feral minnow
#

anyway thx guys and @tired root if you try to relax and ask what the person is trying to do this would be better😀

tired root
#

I am relaxed

#

I just oppose control through restriction

#

And you are losing users by doing that in the future

#

but if you want to do it that way, then more power to you

feral minnow
#

Do you think if you send too much requests to another website with no time to cool down this will be good??!

tired root
#

Oh you are talking about web scraping. Say that :P. Well, depends on if you breach their TOS....

#

Also, you can use caching methods

#

and make sure to use the ETag header

#

then you simply get a 302 if the data hasn't changed

feral minnow
#

Well I didn't find any TOS... about the second thing whats is it?

tired root
#

The ETag or entity tag is part of HTTP, the protocol for the World Wide Web. It is one of several mechanisms that HTTP provides for Web cache validation, which allows a client to make conditional requests. This allows caches to be more efficient and saves bandwidth, as a Web s...

feral minnow
#

what about caching methods?

tired root
#

cache popular content on your end, but again, that depends on what you are delivering

#

in case of your tube videos it is probaly not legal

feral minnow
#

nope its the one im talking about now is not about yt

#

Anyway thanks for the help👍

smoky skiff
#

Anyone familiar with flask socket?

socket.emit('update', data={ "message": "Hello this is the message", "percent": "10" }) socket.sleep(0)

I'm trying to emit a response at certain point of my function

emitting event "update" to all [/]
a69ccc7849b8483891571dc88d9ac14f: Sending packet MESSAGE data 2["update",{"message":"Hello this is the message","percent":"10"}]

This is what I get in logs... but my frontend isn't receiving this emit

socket.on('update', (data) => {
            console.log("is this even getting called")
            console.log(data);
        })
quiet mirage
#

Today, I finished going through the Flask blog tutorial. Really happy with the results, and the framework in general. Going to go through their "ideas to continue" list at the end and make Flaskr into something of my own

wild oar
#

so, I'm using flask

#

and flask-socketio

#

for server

#

and javascript socket.io.js for client

#

<input type="file" id="application-icon" name="img" accept="image/*">

#

I have this input

#

And I want to emit the file

#

Maybe something like

#

socket.emit('send the file over event', { file: $('#application-icon') })

#

I've searched all over but I couldn't find any way to do it through socket.io.js

#

And no way to receive it through flask-socket-io

#

Should I just use POST requests?

feral minnow
#

@quiet mirage Great man and yes flask is amazing keep going

quiet mirage
#

Thank you, def appreciate it. Been wanting to put a website together for the longest

somber fiber
#
print(response.text)```
#

for some reason when I run this code response.text prints just a long string of characters that look like this Z3ғڋ#R�z Tgb���ן>���M��^N��$��S�ܑ�O}=�o�fx~t�;��L��N�?nG�X�z"��7
does anyone have any solutions?

feral minnow
#

you are trying to send a request to a website?

#

@somber fiber you can try requests

#

response= requests.get("https://www.sneakersnstuff.com/", headers=headers)

#

you have to import it first

native tide
#

JavaScript is hard and I hate it.

#

I just need to get a book and read it, from the beginning, instead of just trying to use it.

#

This is Javascript to me

(function () { 
  .wgfdsafs => function ([$bullshit, $poop) {
})];
) function () { someOtherStuff;
)}();
#

And im just like what the fuck is all the punctuation

#

lol

feral minnow
#

python is the best(:

native tide
#

Its better when its able to do the job but its not always.

#

I need to just use vanilla, any time I need JS, and stop trying to use these frameworks.

#

The thing is, when I started Python, I enjoyed every moment of it. All the little details from the beginning, it was so fun for me and interesting.

#

JavaScript is literally a means to an end.

#

I hate every moment I have to touch it

#

So I try to skip things and make it worse.

#

I just need to learn it better and deal with it

feral minnow
#

man you have feelings for python lol

#

yup

#

if you need it learn it

native tide
#

I do have feelings for Python.

feral minnow
#

for me I just learn some html and css for the front end and everything else is from bootstrap (:

#

ya its amazing

native tide
#

If I had to describe my relgiion, I would say Python.

feral minnow
#

I love it

native tide
#

I know HTML and CSS pretty well.

raw imp
#

I am building an electron app but one of the modules that I am using requires NODE v8.11.3 Electron was built using v12.13.0
When I install electron I get this error:

Is there a way I could get around this?

native tide
#

I have no problem there

feral minnow
#

nice

#

when you started

#

programming ?

native tide
#

idk if it fits in web-development. i have a problem with requests and beautiful soup

feral minnow
#

@native tide the Elem is returning None

native tide
#

but it prints keywords

feral minnow
#

can i see the value of it?

native tide
#

print(keywords1) returns e.g. this: Metallzuschnitt, Kunststoffzuschnitt, Blechzuschnitt, Metallkonfigurator, ProKilo

feral minnow
#

oh so what are you trying to do?

native tide
#

well i want to crawl websites and take their keywords and append them to a list

#

so i do a request, take beautifulsoup to extract the content and then i want to append it to 'data'

#

this is a traceback to the code that i posted in help-sodium:

#
Traceback (most recent call last):
  File "C:\Users\LuMi\AppData\Local\Programs\Python\Python38-32\Lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\Users\LuMi\Desktop\Programming\saas\flask\routes.py", line 723, in run
    worker(url)
  File "C:\Users\LuMi\Desktop\Programming\saas\flask\routes.py", line 733, in worker
    keywords1 = soup.find("meta", {"name":"keywords"})['content']
TypeError: 'NoneType' object is not subscriptable
Metallzuschnitt, Kunststoffzuschnitt, Blechzuschnitt, Metallkonfigurator, ProKilo
#

notice how it says typeerror even though it prints the keywords

feral minnow
#

oh so you wanna take the items in the list

#

and append them

#

to another list?

native tide
#

yes

#

i want to accumulate from different websites and they all shall append them to data

feral minnow
#
     data.append(key)```
native tide
#

but i have different threads that all write into data

#

thats why i use acquire and release so that they do not interfere

#

do you think it is a multithreading problem and not related to the BeautifulSoup?

feral minnow
#

give me a sec

#

Im not sure what are you trying to do

#

does strip return a value??

#

yes

#

i think

jade egret
#

remove the ['content'], only do that after checking its not None

feral minnow
#

print(keywords1==None)

#

try it

feral minnow
#

Guys anyone know why if form.validate_on_submit():

#

is not working

#

and here's the flask class form

#
    Link = TextField("Enter the manga link here")
    startChapter= SelectField("Start Chapter", choices=[])
    endChapter= SelectField("Start Chapter", choices=[])
    submit= SubmitField("Choose")```
#

I have a csrf_token at the html file

#

any help?

nimble epoch
#

@feral minnow still have problem with your form?

feral minnow
#

@nimble epoch yup

hollow berry
#

help

hearty oak
#

anyone here using FastAPI for webapps development ?

gilded dragon
#

So I have a python script that I want to run on my device that I'm hosting a rudimentary django server on. I'm trying to get a button on my webpage, via javascript, to cause that python script to run and do its thing. I've figured out that it looks like I need to make an ajax request, but I can't figure out where to go from there. Pretty much all documentation is based around sending some info to the server and then getting some info back, and the documentation kind of explains all of that in detail, but that's not what I'm trying to do. I'm just trying to run a script on the machine.

What is this called? Like what are the keywords for this issue so I can google search them and at least get a lead?
Please @ me if you decide to respond. Thanks <3
Also posting this in a help channel, cuz I figure this channel is dead this time of night.

supple loom
#

Anyone uses Xpath helper extension in chrome?

native tide
#

what is the best framework for backend use

vagrant adder
#

it depends what are your needs

#

what do you plan on building

native tide
#

hi team I need a little help with django models if anybody here is willing 🙂

#

I have 3 models from django.db import models, connection
class Users(models.Model):
username = models.CharField(max_length=30)
def str(self):
return self.username
class Buch(models.Model):
name = models.CharField(max_length=4)
user = models.ManyToManyField(Users)
def str(self):
return self.name
class AdmList(models.Model):
adm = models.CharField(max_length=30)
bukrs = models.ManyToManyField(Buch)
user = models.ManyToManyField(Users)
def str(self):
return self.adm

#

and i need a hierarhical view, in other word dependant dropdown query... What do you think..

feral minnow
#

Guys anyone know why if form.validate_on_submit():
is not working
and here's the flask class form

    Link = TextField("Enter the manga link here")
    startChapter= SelectField("Start Chapter", choices=[])
    endChapter= SelectField("Start Chapter", choices=[])
    submit= SubmitField("Choose")```
I have a csrf_token at the html file
patent lily
#

you dont have any validators?

#

you'd need to import from wtforms.validators @feral minnow

surreal tangle
#

Hey, anyone familiar with progressive web apps and flask? I added the pwa logic to flask-cookiecutter app, and it seems to mess with form submit logic

#

As far as I can tell, with the PWA enabled the login form submit sends a GET instead of POST, causing the page to refresh instead of checking user login

nimble epoch
#

@surreal tangle did you add it like:
if request.method == “POST”:
.....
elif request.method == “GET”:
....

surreal tangle
#

the login route is unchanged from flask-cookiecutter:

@blueprint.route("/", methods=["GET", "POST"])
def home():
    """Home page."""
    form = LoginForm(request.form)
    current_app.logger.info("Hello from the home page!")
    # Handle logging in
    if request.method == "POST":
        if form.validate_on_submit():
            login_user(form.user)
            flash("You are logged in.", "success")
            redirect_url = request.args.get("next") or url_for("user.members")
            return redirect(redirect_url)
        else:
            flash_errors(form)
    return render_template("public/home.html", form=form)
#

sorry, pasted wrong method

nimble epoch
#

No need to add request.form in the form

surreal tangle
#

@nimble epoch so yes, the POST/GET as you wrote

nimble epoch
#

And add a if request.method == “POST”: