#web-development

2 messages ยท Page 110 of 1

cold haven
#

do you need to use something like docker if you are going to store Django on a server?

#

for Deploying it?

#

Or would Django have something built in for that?

quick schooner
#

hello all
i'getting my hand on Django queries
and i am supposed to have 80ish entries for a model
this model have a link in the format following DATE_XXX@YYY
if i do
e_tor = e.filter(boxscore_link__icontains='XXX')
it will only filter those with the format @XXX and not the ones with XXX@YYY why ?
because i want to get all objects where DATE year = 2019 and XXX is present in field

cold socket
#

This works just fine when running it locally on my system

warm igloo
#

@cold socket it can't do your import .. my guess is maybe in your dockerfile you're not installing your reqs?

#

you could perhaps bash into your container to see if everything is where you expect it to be but it seems like though it can see app it can't see Stores

cold socket
#

Stores is a class in the app.py file

warm igloo
#

ah, interesting

cold socket
#

and Im importing it in another file called checker.py

#

and theyre in the same directory

gaunt marlin
#

hello all
i'getting my hand on Django queries
and i am supposed to have 80ish entries for a model
this model have a link in the format following DATE_XXX@YYY
if i do
e_tor = e.filter(boxscore_link__icontains='XXX')
it will only filter those with the format @XXX and not the ones with XXX@YYY why ?
because i want to get all objects where DATE year = 2019 and XXX is present in field
@quick schooner are you sure your filtering is correct ? because i tried on my machine, filter still able to find with icontains="XXX" and found example data with "XXX@2019"

quick schooner
#

i found my error

#

the TOR@ doesnt appear in my field in fact !

#

my bad

#

there

gaunt marlin
#

oh ok glad you figured it out

quick schooner
#

i just did right now lol

#

printing everything always work

gaunt marlin
#

yeah debug always help ๐Ÿ˜„

quick schooner
#

if i show you my models file would you be able to tell me waht to improve ? because i'm really struggling rn on how to model efficiently my models to make simple queries

gaunt marlin
#

sure, if i can't help other people can help too

#

post it away

quick schooner
#

i have many queries i want to make

#

but a good start would be the following

#

find all Linescores fitlering by Season year and Team abbreviation

#

i am wondering if i really need to have so much sub classes to my main Event class

#

because my Event is linked to a Boxscore which is linked to a Linescore

gaunt marlin
#

yeah let me read over and see

quick schooner
#

dw thanks a lot

gaunt marlin
#

a suggestion when you have troubles figuring out models it's easier to see with a UML diagram of tables

quick schooner
#

nice !

#

its a mess lol

#

i made a Linescore as a sub of boxscor just to organise better (think it is ) from just having Linescore linked to Event just as betpp class

#

so i want to get all linescores of a team Events from a certain year how would i do that please ?

#

one of the issue i see is i cant filter my Events by team since i dissociated home and visitor Team in event

gaunt marlin
#

@quick schooner from the UML you can see that Linescore FK to Team and FK to Event

quick schooner
#

yes

gaunt marlin
quick schooner
#

so i should filter Event there since it s the only class with a date right ?

gaunt marlin
#

yes filter by Event.date

#

i see 2 path you can choose:

  • Linescore -> Boxscore(boxscore_id) - > Event(event_id).date
  • Linescore -> Team(visitor_team) ->Event(visitor_team but the FK relation is reversed)
#

so i suggest query by the first method

quick schooner
#

ok

gaunt marlin
#

because event and Team has opposite FK relation so it's hard to do query on

quick schooner
#

what do u mean by opposite foreign key ?

#

i feel that boxscore class is useless

gaunt marlin
#

filter(Linescore__Boxscore__Event_date__year=YYYY)

#

reverse i mean if you look at the UML

quick schooner
#

ok

gaunt marlin
#

boxscore contain fk of event

#

but team don't contain fk of event

#

but it reverse: event has fk of team

quick schooner
#

but i could shortcircuit it and fk linescore to event no ?

gaunt marlin
#

yeah you can

quick schooner
#

ok

gaunt marlin
#

i don't know basketball so i'm not too familiar with it's leauge system ๐Ÿ˜„

quick schooner
#

haha its ok dw ^

gaunt marlin
#

but yeah have Linescore FK with event is easier

quick schooner
#

thats what i thought yes

gaunt marlin
#

you can have Linescore.event_id

#

in the real life i think it's the same score usually connected to event leauge

quick schooner
#

well in my logic

#

u have event

#

event has a boxscore wich will score all infor relatives to scores like linescore with quarter scores and playerstats also in boxscore

#

but it is overflow yes

#

so o k i load all events

gaunt marlin
#

possibly, but database is not my main field, you can ask about designing database in #databases ๐Ÿ˜„

#

i can only help with framework stuffs like query,... ๐Ÿ˜›

quick schooner
#

i have loaded all games from 2019 now with date__year ='2019'

gaunt marlin
#

nice

quick schooner
#

now how can i filter with teams ?

#

because my issue is

#

the fk to Team

#

is showing home or visitor team only

#

so i an only filter by home or visitor and not by simple Team

#

like if i have PHI@TOR

#

here visitor is Phila and home is Toronto

#

with my model i can only model from home or visitor team right

#

but if i want to get all games wether Toronto is at home or visitor how can i do that ?

gaunt marlin
#

which table represent game?

#

it's event or linescore?

quick schooner
#

yes Event is the class for game

gaunt marlin
#

@quick schooner use OR or IN statement in your query

quick schooner
#

let me check IN

#

is this an AND ?

#

e_tor_2019 = e_2019.filter(visitor_team__abbreviation='TOR' AND home_team__abbreviation='TOR')

#

i tried this

gaunt marlin
#

you looking if TOR with OR right ?

#

or is in 1 of those

#

and required both need to be TOR(which is not possible)

quick schooner
#

eithe one or other so its a or u are right

gaunt marlin
#

nvm

#

it's 1 result

#

you have to use OR ๐Ÿ˜„

quick schooner
#

^^

gaunt marlin
#

i posted above how how to use OR in django query

#

use Q objects

quick schooner
#

Its working !!!!

#

yes thats pretty efficient and simple indeed

gaunt marlin
#

nice

quick schooner
#

i tried to mix the three queries

#

where e is the list of events

#

but i still have other years events

#

what is wrong here ?

gaunt marlin
#

because you use or

#

the logic is

quick schooner
#

ohhh

#

yes of course

gaunt marlin
#

(visitor team = 'tor' OR home_team = 'tor') AND date__year=2019 @quick schooner

#

is this easier to see ?

quick schooner
#

the AND gives me syntax error

gaunt marlin
#

so it should be
e.filter((Q(visitor_team__abbreviation='TOR',) | Q(home_team__abbreviation='TOR')), date__year='2019')

#

django ORM don't have AND syntax

#

and is , in query

quick schooner
#

okkk

#

got it

#

works great

#

i cannot thank you enough for sharing you knowledge with me in a sympathic and efficient and patient way ๐Ÿ™‚

gaunt marlin
#

glad to help

quick schooner
#

and now

#

from this list of eents

#

if i want to access the data in the linescore ?

gaunt marlin
#

you have list of events

#

and your linescore have fk to events

#

so the logic should be linescore has event IN events

#

so this is where the __in query come in

#

but __in only work with a list

quick schooner
#

ok

gaunt marlin
#

and you need a list of event id

quick schooner
#

ok

gaunt marlin
#

to get id list of query you use .values_list('id', flat=True)

quick schooner
#

well linescore has fk to boxcore which has fk to event in the current state

gaunt marlin
#

at your event query you made you add that

#

now your a variable is a list of id

quick schooner
#

ok yes

#

it gives me a query set of Ids nice

gaunt marlin
#

@quick schooner oh ok so you have to do

Linescore.objects.filter(boxscore_id__event_id__id__in=a)
quick schooner
#

ok i got Related Field gort invalid lookup

gaunt marlin
#

can you post the full error ?

#

!codes

lavish prismBOT
#

Here's how to format Python code on Discord:

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

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

gaunt marlin
#

i edited the query above a few times so i guess you copy the wrong thing

#

Linescore.objects.filter(boxscore_id__event_id__id__in=a)

quick schooner
#

ok i suppose yes

#

and a

#

would be a event id right ?

true falcon
#

Hey i am trying to deploy my flask web app in heroku but it is saying application error

This is my error

 at=error code=H14 desc="No web processes running" method=GET path="/" host=simply-con.herokuapp.com request_id=996bdf6d-5a93-48b0-bc5a-b95383427023 fwd="49.207.138.206" dyno= connect= service= status=503 bytes= protocol=https

And here is my code https://github.com/Prasanna-Natarajan-3595/Trash

Can anyone help me what is wrong pls.

gaunt marlin
#

@quick schooner yes is the list of events you got from the one before that

quick schooner
#

oh it is a list ok

#

in checks the list ok

#

gets me an empty queryset unfortunately

gaunt marlin
#

really ?

#

i though the events query worked for you earlier

quick schooner
#
Out[305]: <QuerySet [107088, 107102, 107119, 107128, 107141, 107163, 107178, 107197, 107207, 107223, 107241, 107245, 107263, 107277, 107305, 107328, 107341, 107352, 107367, 107381, '...(remaining elements truncated)...']>

In [306]: Linescore.objects.filter(boxscore_id__event_id__id__in=a)
Out[306]: <QuerySet []>

In [307]: b = Linescore.objects.filter(boxscore_id__event_id__id__in=a)

In [308]: b
Out[308]: <QuerySet []>
gaunt marlin
#

a haha no you haven't applied .values_list('id', flat=True) to a yet

quick schooner
#

i believe i did ๐Ÿ˜ฎ

gaunt marlin
#

you flow should be like so

a = Events.objects.filter((Q(visitor_teamabbreviation='TOR',) | Q(home_teamabbreviation='TOR')), date__year='2019').values_list('id', flat=True)

b = Linescore.objects.filter(boxscore_id__event_id__id__in=a)
#

it's like this ?

#

are you sure that in your data b has any values ?

#

linescore that contain boxscore that contain event id year=2019 ?

quick schooner
#

In [316]: a
Out[316]: <QuerySet [107088, 107102, 107119, 107128, 107141, 107163, 107178, 107197, 107207, 107223, 107241, 107245, 107263, 107277, 107305, 107328, 107341, 107352, 107367, 107381, '...(remaining elements truncated)...']>

In [317]: b = Linescore.objects.filter(boxscore_id__event_id__id__in=a)

In [318]: b
Out[318]: <QuerySet []>
#

welll idk

gaunt marlin
#

maybe check your database

quick schooner
#

what should i be looking for in this case ?

#

i have 3870 Linescores

gaunt marlin
#

see if any linescore has event_id = one of those results from a


#

are you using mysql or postgres as your database?

quick schooner
#

postgres

gaunt marlin
#

can you access your postgres data with pgadmin ?

quick schooner
#

yes

#

i have it

gaunt marlin
#

for query IN statement of postgres

SELECT  *
FROM    table
WHERE   some_id = ANY(ARRAY[1, 2])
#

you copypaste the a list in array part

quick schooner
#

i tried with one id

#

select * from public.stats_event where id= '107088'

#

and it returns the row correctly

gaunt marlin
#

i don't see stats_event column in your database

#

or did i missed it ?

vestal hound
#

huh.

gaunt marlin
#

oh nvm it's table name

vestal hound
#

why are you doing it this way

#

is there a reason?

quick schooner
#

yes its table

vestal hound
#

like with two separate querysets

quick schooner
#

i am beginner

#

figuring the best ways to do queries at the moment ๐Ÿ™‚

vestal hound
#

like do you need both a and b?

#

or what

#

or do you only need a because you want those IDs to query b

quick schooner
#

i m looking to acces Linescore stats from a query set of Event

gaunt marlin
#

you can see above he querying for linescore that contain event with year=2019 and has (home_team OR visitor_team = 'TOR')

#

so it should be 2 queries

quick schooner
#

queryset of event being games wher etor is visitor and home and year is 2019

gaunt marlin
#

a itself contain many filter logics so it need to be separate

#

i'm thinking his database might not has the data satisfied his query

quick schooner
#

possibly also

gaunt marlin
#

can you access django admin ?

#

you can search from there

#

generate admin of linescore

quick schooner
#

not sure how

gaunt marlin
#

oh then nvm

vestal hound
#

as in

#

my question is

#

do you need the queryset of Event or not?

#

like independent of the queryset of Linescore

quick schooner
#

i'm not sure tbh

gaunt marlin
#

you should post your logic

vestal hound
#

or do you just want the Linescore instances

#

that correspond to certain criteria over events?

#

okay, let me put it this way

quick schooner
#

i think i just want and need the Linescores

vestal hound
#

say you solve your problem with the above querysets a and b

#

do you need a for anything?

#

okay.

#

can you explain again

#

which linescores you need?

quick schooner
#

but i cant filter the linescores with my model

#

lets say i need

#

all line scores

#

of games of 2019 of the team TOR

vestal hound
#

okay

#

can you post your models

#

which fields would those be?

#

do you have like a DateTimeField that corresponds to the game date etc.

#

and which model is that in?

quick schooner
#

also an image of it

#

and the Linescore fieelds i'm intersted in Linecore

vestal hound
#

okay minor thing

#

use UpperCamelCase for your model names

quick schooner
#

ok

vestal hound
#

actually this is a relatively major thing

#

it matters in Django

quick schooner
#

got it

vestal hound
#

normally what you call your classes doesn't really matter apart from being a minor eyesore but I don't know how that would screw with Django's conventions

#

anyway

#

okay so

#

Linescore.objects.filter(Q(visitor_team__abbreviation='TOR') | Q(home_team__abbreviation='TOR'), boxscore__event__date__year=2019)

#

incidentally

#

your Boxscore related_name for the event PK is weird

#

related_name is what the other side calls you

#

so like

#

Boxscore.event -> the Event relating to boxscore

gaunt marlin
#

you missed the OR statement

#

now both teams have TOR

quick schooner
#

it is confusing mee also i just set it up so that i didnt havee 'clashes' from django

vestal hound
#

you missed the OR statement
@gaunt marlin wups yeah, fixed

gaunt marlin
#

basic principle of naming in python usually
class: CamelCase
variable, function: use _ for separation

vestal hound
#

it is confusing mee also i just set it up so that i didnt havee 'clashes' from django
@quick schooner you probably have clashes for another reason

#

in any case, good naming is very important

#

that related_name is basically asking...

#

what do you want to call the Boxscore models that are related to an Event?

#

and right now you have event.event

#

because you set your related_name to 'event'.

#

oh my GOD you called your related field event_id?

quick schooner
#

thats bad yes

vestal hound
#

just call it event

#

in your Boxscore model

#

yeah, you need to fix that or the query I gave you won't work

#

alternatively you can change the last filter to boxscore__event_id__date__year=2019, which is...pretty weird.

gaunt marlin
#

also in Django don't name field with _id because django will auto add _id at the end of column name
for example:

user_id = ForeignKeyField, django will auto set in database column name = user_id_id

quick schooner
#

well since myy model was already confusing me

#

yes i put event_id in boxscore to remberber it was the foreignkey towardds the even id haha

#

ok i didnt know that nice

#

could you provid a better models.py architecture i could use ?

#

i feel that this is way more omplicated how i did it than how it is supposed to be done with django logic

gaunt marlin
#

it's not actually related to Django but your database design

quick schooner
#

i feel itt is poorly designed

#

what should i precisely ask theree please ?

gaunt marlin
#

you can post the screen shot of your database

#

and ask for feedbacks

quick schooner
#

ok cool doing it rn

strange ocean
#

hey guys i have a question

{
  "data1": {
  some data   
  }
}

i want to append data2 to this file in the exact same way as data1 is

spiral smelt
#

You can add using obj["data2"] = data2

#

"data2" would be the key, data2 is the variable storing the stuff after :

gentle ingot
#

Im working though CS50 Web Development. Just to be sure i understand the layout (typing it out without googling helps me commit to memory) My website is bascially an app. Within that app, i have to define the webpages in urls.py and views.py which assigns a url path to each html file and renders the webpage based on which html file is called (respectively). These python files allow for coding in the html file as well as dynamiclly updating paths right?

spiral smelt
#

urls.py maps a url to a python function in your views.py

#

The functions in views.py renders the template htmls

#

Also yay to cs50 web

gentle ingot
#

HTML and CSS lecture were easy. Did that in like a day. I have to break up lecture 3 into multiple days as to not overwhelm myself and actually take in the info. Thanks for the response.

low saddle
#

Hi hoping to get some advice.

Is there any good python web framework, that can create a web server while at the same time be able to send via web sockets every few minutes?

toxic flame
#

Django & flask sir

#

Is very good

vestal hound
#

Django or Flask

#

also note that you'll need a separate library to handle websockets

#

neither of them do out of the box

mental prawn
#

.

tame kelp
#

does anyone know why my main.css file in my static folder not loading ?(flask)

#

I used url_for(), and i have it imported too, idk why it isnt working

#

like it didnt take full affect..

regal furnace
#

Good day! I need help or tip how to upload info from file to Django app db.
I need to upload info from gist file(Myfile.CSV) to my Django app database. Can anybody give me suggestion how to do it more correctly? I have gist file which is located on github. It's a csv file wich containes 3 columns(number, name, colour) and several rows. So I need to upload(save) to existing Django project info from this file and after it change names of columns to different one.

https://stackoverflow.com/questions/64675291/how-to-upload-gistcsv-file-to-django-app-database

tame kelp
#

nevermind i figured it out, my static folder was inside my templates one

cobalt cedar
#

Can someone tell me this?
I'm deploying my flask application on aws ec2 engine.
I created a default vm and ssh'ed into it.
Firstly I disabled all incoming traffic
Then I allowed ssh on port 22 and http on port 80.
I downloaded my code from github.
Downloaded all packages required.
And ran the flask app with debug ttrue for development testing.
The app ran successfully there's no error, but on visiting the public ip the page isn't loading neither the debug is showing the get request made.

outer apex
#

@tame kelp What does your code for that look like?

tame kelp
#

i figured it out

#

my static folder was inside my templates one

#

so basically my route wasnt correct

grizzled sand
#

@devout coral yeah in generally. Rubber duck debugging is works ;)

cold haven
#

good morning

stable kite
#

How to make API POST request in js?

cold haven
#

ajax

#

here is a good resource

native tide
#

How do I verify?

stable kite
#

@cold haven i am getting an cors error

#

i am sending request to my drf

cold haven
#

can you show me some code?

native tide
#

U need a library called django cors I think

#

Search it up and read the docs on that then you can allow incoming requests from allowed hosts

stable kite
#

@stable kite u need to set allowed hosts in settings.py
@native tide i have done that

#

U need a library called django cors I think
@native tide i will try it

native tide
#

Uhhh what auth method are u using

#

Yeah to use allowed hosts you need the library

#

Corsheaders

stable kite
#

i am using drf

native tide
#

And then set it in installed apps

#

Yeah but you need corsheaders to set allowed hosts

stable kite
#

ok

#

i will try that

#

thanks

digital hinge
#

does anyone know how i would go about showing the 'print' commands from my script to show up on my html home page when the user presses send? This is my flask app:

from flask import Flask, render_template, request
from My_script import resend_data

app = Flask(__name__)
@app.route('/')
def main():
    return render_template ("home.html")

@app.route('/process', methods=['POST'])
def process():
    # Retrieve the HTTP POST request parameter value from 'request.form' dictionary
    _username = request.form.get('username')  # get(attr) returns None if attr is not present
    _password = request.form.get('password')
    _UID = request.form.get('UID')
    # Validate and send response
    resp = resend_data(_username, _password, _UID) 
    #subprocess.call(["python","myscript.py"], shell=True)
    return render_template("some_page.html", response=resp)
#def response():
#    return render_template ("out.html")
if __name__ == '__main__':
    app.run(debug=True)
cold haven
#

you can't use the print() function in an html. It's python

proper owl
#

@digital hinge What I usually do is render the same html template but in different view and flash message. Do you only want to let user know login done OK?

cold haven
#

I don't know what you are doing.

#

I'm learning this too.

digital hinge
#

@proper owl I have a form that the values _username, _password and _UID are being entered. When they click "submit" it processes the script. The Flask terminal shows the PRINT objects but id like to show them on the html page (Ajax maybe?)

cold haven
#

send them to the view yeah.

proper owl
#

to do it simple you can pass something to render_template("some_page.html", response=resp,uid = _uid, username = _username)

#

and in html template acces it by {{username}} {{uid}}

hybrid patio
#

Hello Guys

#

I have litte problem with Flask

#

Is there someon who understand Flask?

proper owl
#

it depends on problem complexity xd

digital hinge
#

i want it to show on the home.html. The some_page i have is actually the 'done result'": ```html

<html>
<head>
<title>Some</title>
</head>
<body>
The response was:
<p>{{ response.reason }}</p>

<h2>Download a file</h2>

<p>
<a href="{{ url_for('.download_file') }}">Download</a>
</p>
</body>
</html>

hybrid patio
#

ok

#

I deleted one script with flask and I dont remeber when this script was turn on or not

digital hinge
hybrid patio
#

so I have another script with flask .. and when I turn on this I see in localadress old resoult

#

do you understand me?

proper owl
#

@hybrid patio maybe try to refresh your browser by Ctrl + F5?

#

i had same problem at the beggining with css style not updating

hybrid patio
#

๐Ÿ˜„

#

I show you simple exam

velvet sigil
#

Hey guys, I'm trying to build a simple Chat application using Django. Found an official Django tutorial online - https://channels.readthedocs.io/en/stable/tutorial/

When I completed part 2, I'm facing an issue. My issue is as below. :

When 1st browser joins a room it works just fine. But the moment a new browser session joins the same room, the first session does not get the messages and 2 messages are sent to the latest browser session.

If a third browser session joins the room, 1st and 2nd sessions don't get the messages and the third session gets all the 3 messages.

I followed every step meticulously but not able to fix the issue.

Can anyone help me, please?

hybrid patio
#

from flask import Flask

app = Flask(__name__)

app.route("/")
def simple_text():
    return "Hello everyone"


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

#

why show me text Hello in my browers

#

maybe cookes?

wise phoenix
#

keep getting 400

#

why? any ideas

hybrid patio
#

๐Ÿ˜„

digital hinge
#

So im wondering if there is simple way to put every print command from a script on the webpage 'home.html' instead of the console of the server?

native tide
#

webpage script

#

ill assume this means javascript

#

use console.log in the script it will print to the client console

nimble epoch
#

@digital hinge still have problem?

digital hinge
#

Yes, just wanting to show the output of my ython script on my html page when they hit the send button

nimble epoch
#

ok what you want to do exactly

#

?

digital hinge
#
from flask import Flask, render_template, request
from My_script import resend_data

app = Flask(__name__)
@app.route('/')
def main():
    return render_template ("home.html")

@app.route('/process', methods=['POST'])
def process():
    # Retrieve the HTTP POST request parameter value from 'request.form' dictionary
    _username = request.form.get('username')  # get(attr) returns None if attr is not present
    _password = request.form.get('password')
    _UID = request.form.get('UID')
    # Validate and send response
    resp = resend_data(_username, _password, _UID) 
    #subprocess.call(["python","myscript.py"], shell=True)
    return render_template("some_page.html", response=resp)
#def response():
#    return render_template ("out.html")
if __name__ == '__main__':
    app.run(debug=True)
nimble epoch
#

ok is My_script module your own script?

digital hinge
#

the home.html has a form that gets a couple of vlues and passes these value to y python script. The server console shows me the print values but i would like them to show on the html page as well

#

yes

nimble epoch
#

ok any error?

digital hinge
#

the resend_data is the function from My_script that launches. No errors runs beutifully, just no process bar or anything that tells the user its working

#

so i was hoping i could display the print log after 'send' has been press on the 'home.html' form

nimble epoch
#

what it does maybe your resend_data method is wrong?

#

what the mehod does? maybe itll help more

digital hinge
#

Everything is working. Im just trying to show the script is processing on the client side. So I have a server with Flask, app.py (flask app), that launches the My_script function when the home.html form is filled out and 'send' is pressed. on the Flask run terminal i can see all the objects its 'printing' but i want to show this log as a stream on the html page

nimble epoch
#

your resend_data has parameters but im not sure where the problem is because i think the flask server is working good

#

maybe theres something wrong with your own module

#

and im seeing your some_page template. i cant see any method views named download_file

digital hinge
#

some_page is the page that appears after the script has completed

nimble epoch
#

url_for is usually used for a method name

#

i dont think there gotta be a dot before it

digital hinge
#

download_files downloads the zip file i create with the My_script.

#
@app.route('/download')
def download_file():
    #path = "html2pdf.pdf"
    #path = "info.xlsx"
    path = f"{_UID}.zip"
    #path = "sample.txt"
    return send_file(path, as_attachment=True)
nimble epoch
#

so theres a dot in here url_for('.download_file')

#

you placed it before your methodview name

digital hinge
#

everything works, just want to make this here in "home.html" so show the output of the My_script ```html
<form action="process" method="post">
<input type="text" id = "UID" name = "UID" placeholder="Enter URLโ€">
<input type="text" id="username" name = "username" placeholder="Usernameโ€">
<input type="password" id="password" name="password">
<button class="ui-component__password-field__show-hide" type="button" onclick="text()" id="button">Show</button>
<input type="submit" id = "btnSubmit" value="SEND">
</form>
<script>
<p>{{ output }}</p>

nimble epoch
#

i want it to show on the home.html. The some_page i have is actually the 'done result'": ```html

<html>
<head>
<title>Some</title>
</head>
<body>
The response was:
<p>{{ response.reason }}</p>

<h2>Download a file</h2>

<p>
<a href="{{ url_for('.download_file') }}">Download</a>
</p>
</body>
</html>

there is a dot(.) before your {{ url_for('.download_file') }}

#

remove it

digital hinge
#

Okay

stable kite
#

U need a library called django cors I think
@native tide thanks it worked

digital hinge
#

django and Flask?

stable kite
#

django and Flask?
@digital hinge ??

digital hinge
#

Sorry, thought that was the response to my question about Viewing real-time console on a web page with Flask python

#

@nimble epoch Any idea how i can View real-time console on a web page with Flask python for the home.html when this is pressed: value="SEND

nimble epoch
#

usually javascript used for real-time webpages but im not sure that i got your right?

digital hinge
#

so the flask console is the python output. Thats what im after

cold haven
#

what type of service are you trying to make?

nimble epoch
#

@app.route('/button/')
def button_clicked():
print 'Hello world!' #output in the console
return redirect('/') #output in the webpage

cold haven
#

@digital hinge I wouldn't go about writing to a client console at all in that case. I would have an alert in the form of a popup show after pressing a button. Here is a resource for that specific action : https://www.w3schools.com/js/js_popup.asp

digital hinge
#

@cold haven What about a process bar then?

#

@nimble epoch that is only showing a print, ot the output from the script My_script.py

cold haven
#

I would make a request for a resource on the server by using an ajax post, and then returning it, and then you can put it wherever you want in the view.

#

Maybe you would want it in a popup box.

nimble epoch
#

@digital hinge you have create two flask app?

cold haven
#

This sounds more like a job for Django.

nimble epoch
#

@cold haven no difference

cold haven
#

ofc it's different

nimble epoch
#

you want to create just a download button right?

digital hinge
#

no My_script downloads files, its the wait time i want to show the python console output on the home.html page

nimble epoch
#

so you gotta return it

digital hinge
nimble epoch
#

you gotta use redirect using flask

#

you want the client download the file then get redirected to the other page?

digital hinge
#

the files download when they press the 'send' button and it can take up to 5 min

cold haven
#

you want to avoid sending redirects from the client and use a router on the server-side.

digital hinge
#

need like a process bar or to show the server console output for the print commands so the user can see the files are downlaoding

nimble epoch
#

so...

balmy stag
#

I think what @digital hinge want is to display the logs created by his script WHILE it's running. The solution you just linked seems like a good idea but it's a bit hacky and not optimized. A solution could be to use websocket, but I've never used Flask, I don't know how it can be handled.

cold haven
#

you want to create a download bar for what exactly? requests are almost instantaneous except when downloading GBs of info. @digital hinge

nimble epoch
#

yeah not sure but i think hes right theres extension called flask_socketio i think thisll help

#

i dont know exactly how it works or does it work for you but...

digital hinge
nimble epoch
#

yep

#

and theres a tutorial in youtube...

balmy stag
#

You first need to connect your front (JS) to a websocket Flask view that emits an event whenever a log is created (that's the hard part), when the JS gets an event it displays it in the html page.

nimble epoch
#

is javasciprt necessary?

cold haven
#

maybe jQuery is better.

nimble epoch
#

that javascript too

cold haven
#

or React

nimble epoch
#

hate javascript

cold haven
#

you could just use the backend flask lib, no?

#

why you need js?

balmy stag
#

Yeah I think it's necessary, you need to make your page dynamic

native tide
#

Hi

#

I need help

#

In choosing

balmy stag
#

Websocket work with an emitter (Flask) and a receiver (JS)

cold haven
#

oh you mean with RESTful API

native tide
#

Flask vs Django for chat app

nimble epoch
#

no difference

digital hinge
#

What about something like this: ```py
@app.route('/yield')
def index():
def inner():
proc = subprocess.Popen(
['dmesg'], #call something with a lot of output so we can see it
shell=True,
stdout=subprocess.PIPE
)

    for line in iter(proc.stdout.readline,''):
        time.sleep(1)                           # Don't need this just shows the text streaming
        yield line.rstrip() + '<br/>\n'

return flask.Response(inner(), mimetype='text/html')  # text/html is required for most browsers to show th$
nimble epoch
#

oh sorry i dont use subprocess

cold haven
#

how else are you going to send requests to the server w/o js is the question, if only you use it for REST I think.

#

you need json objects

nimble epoch
#

@digital hinge try it yourself see it works or not

balmy stag
#

HTTP is not asynchronous, you call it, it gives you an answer right away, so that don't work I think

cold haven
#

back in the day of PHP you would serve a static html from the server and that's it. You would use php forms.

balmy stag
#

The link you gave earlier is maybe simpler, you call a view that gives every log you had so far every X seconds, and place the response in your html body

cold haven
#

you can send a form in htmI believe, you use SOAP

nimble epoch
#

The link you gave earlier is maybe simpler, you call a view that gives every log you had so far every X seconds, and place the response in your html body
so the page reloads every second am i right?

digital hinge
#

@nimble epoch ```py
from flask import Flask, render_template, send_file, request
import time
from My_script import resend_data
import subprocess

app = Flask(name)
@app.route('/yield')
def index():
def inner():
proc = subprocess.Popen(
['dmesg'], #call something with a lot of output so we can see it
shell=True,
stdout=subprocess.PIPE
)

    for line in iter(proc.stdout.readline,''):
        time.sleep(1)                           # Don't need this just shows the text streaming
        yield line.rstrip() + '<br/>\n'

return flask.Response(inner(), mimetype='text/html')  # text/html is required for most browsers to show th$

@app.route('/')
def main():
output = execute('./script')
return render_template ("home.html",output=index)
_UID = None #Global decleration
@app.route('/process', methods=['POST'])
def process():
# Retrieve the HTTP POST request parameter value from 'request.form' dictionary
_username = request.form.get('username') # get(attr) returns None if attr is not present
_password = request.form.get('password')
global _UID #Global Value across functions
_UID = request.form.get('UID')
# Validate and send response
resp = resend_data(_username, _password, _UID)

#classes = resend_data(_UID)
#subprocess.call(["python","myscript.py"], shell=True)
return render_template("some_page.html", uid=_UID, response=resp)

#def response():

return render_template ("out.html")

@app.route('/download')
def download_file():
#path = "html2pdf.pdf"
#path = "info.xlsx"
path = f"{_UID}.zip"
#path = "sample.txt"
return send_file(path, as_attachment=True)
#source: https://www.roytuts.com/how-to-download-file-using-python-flask/

app.run(debug=True)

balmy stag
#

No need to reload if you use JS and ajax

#

I could give you the JS script if you're not confortable with JS

digital hinge
#

return render_template ("home.html",output=index)
^
IndentationError: unindent does not match any outer indentation level

nimble epoch
#

so final answer is YOU SHOULD USE JAVASCRIPT

cold haven
#

maybe you would be better off using typescript and fetch

#

that's what I would do

balmy stag
#

Yeah if you want a dynamic page JS is unavoidable ๐Ÿ˜…

#

maybe you would be better off using typescript and fetch
@cold haven Typescript needs compilation, it seems a bit heavy, plain JS is enough

cold haven
#

typescript is like the updated version of JQuery.

nimble epoch
#

@digital hinge i think i found a new problem in your app in '/' route

cold haven
#

i'm used to using high level abstractions in coding so that's what I would go with in any case. No need to reinvent the wheel for smaller tasks even. Especially if you have lots of sample code available that you can copy/past into different projects.

nimble epoch
#

the output variable youve set in the render_template is set to something called index

cold haven
#

are you going to make a docker container for your server @digital hinge ?

#

I have a good resource for setting that up if you want.

digital hinge
#

No plans for that yet, its just a locally ran server qtm

#

Would it be possible to implement this? I not sure how it would go for multipule users tho?

from flask import Response, escape
from yourapp import app
from subprocess import Popen, PIPE, STDOUT

SENTINEL = '------------SPLIT----------HERE---------'
VALID_ACTIONS = ('what', 'ever')

def logview(logdata):
    """Render the template used for viewing logs."""
    # Probably a lot of other parameters here; this is simplified
    return render_template('logview.html', logdata=logdata)

def stream(first, generator, last):
    """Preprocess output prior to streaming."""
    yield first
    for line in generator:
        yield escape(line.decode('utf-8'))  # Don't let subproc break our HTML
    yield last

@app.route('/subprocess/<action>', methods=['POST'])
def perform_action(action):
    """Call subprocess and stream output directly to clients."""
    if action not in VALID_ACTIONS:
        abort(400)
    first, _, last = logview(SENTINEL).partition(SENTINEL)
    path = '/path/to/your/script.py'
    proc = Popen((path,), stdout=PIPE, stderr=STDOUT)
    generator = stream(first, iter(proc.stdout.readline, b''), last)
    return Response(generator, mimetype='text/html')

@app.route('/subprocess/<action>', methods=['GET'])
def show_log(action):
    """Show one full log."""
    if action not in VALID_ACTIONS:
        abort(400)
    path = '/path/to/your/logfile'
    with open(path, encoding='utf-8') as data:
        return logview(logdata=data.read())
#

ive made a log file in My_script to log the output and save it as logfile.txt

#########
#Logging#
#########
class multifile(object):
    def __init__(self, files):
        self._files = files
    def __getattr__(self, attr, *args):
        return self._wrap(attr, *args)
    def _wrap(self, attr, *args):
        def g(*a, **kw):
            for f in self._files:
                res = getattr(f, attr, *args)(*a, **kw)
            return res
        return g

# for a tee-like behavior, use like this:
#sys.stdout = multifile([ sys.stdout, open('myfile.txt', 'w') ])
class Log(object):

    def __init__(self, path_log, mode="w", encoding="utf-8"):
        h = open(path_log, mode, encoding=encoding)
        sys.stdout = multifile([ sys.stdout, h ])
        sys.stderr = multifile([ sys.stderr, h ])

    def __enter__(self):
        """ Necessary if called by with (or with... as) """
        return self     # only necessary if "as"

    def __exit__(self, type, value, tb):
        """ Necessary if call by with """
        pass

    def __del__(self):
        if sys is not None:
            # restoring
            sys.stdout = sys.__stdout__
            sys.stderr = sys.__stderr__
log = Log("logfile.txt")
nimble epoch
#

def stream(first, generator, last):
"""Preprocess output prior to streaming."""
yield first
for line in generator:
yield escape(line.decode('utf-8')) # Don't let subproc break our HTML
yield last

#

not sure it realy work

#

HTTP is not asynchronous, you call it, it gives you an answer right away, so that don't work I think
as Patiptop said

digital hinge
#

hmm

nimble epoch
#

@digital hinge why dont you just use javascript?

digital hinge
#

Sure, how, im very new to Flask

#

wanted to my my python app web based

nimble epoch
#

its ok with frontend and of course backend too.

cold haven
#

@digital hinge If you want my honest opinion. I would store logs inside of a DB, and Django can do that.

digital hinge
#

Django looks like it starting to be the better choice but ive just started with Flask... i wont give up with it just yet as ill have to redo it all

nimble epoch
#

@digital hinge If you want my honest opinion. I would store logs inside of a DB, and Django can do that.
@cold haven he wants a real time website

digital hinge
#

Even just a progress bar so they know its actually doing something

nimble epoch
#

Django looks like it starting to be the better choice but ive just started with Flask... i wont give up with it just yet as ill have to redo it all
@digital hinge sorry but you cant get what you want in flask ๐Ÿ˜ and even django

stable kite
#

@cold haven he wants a real time website
@nimble epoch you can use firebase if you want it realtime

nimble epoch
#

@nimble epoch you can use firebase if you want it realtime
@stable kite really? using flask?

stable kite
#

@nimble epoch yes

#

you do with any framework

#

as it's a nosql db

nimble epoch
#

@stable kite so you mean real time chat or something like that without js?

stable kite
#

@nimble epoch no i mean if you want realtime db than you can use firebase for anything

balmy stag
#

Here's what I'd make and then I need to get to work @digital hinge:
Flask :

  • have a 'script' view that calls your script just like you did. Instead of printing the log in the console, write it in a log file (save it everytime you write something). Save this file with a name related to the user (could be an autogenerated name in JS that you put in a hidden field in your form).
  • have a 'log' view that takes the famous autogenerated name in parameter, and read the JS file named like that, and returns the content.

Front (JS) :
When you submit the form, add a timeout (https://www.w3schools.com/jsref/met_win_settimeout.asp) that calls your log view using ajax (so the window don't reload). And display the answer of your request in a div in your html page. That'd be a 20 lines script at most, if you want I can write it for you.

#

you can use firebase if you want it realtime
@stable kite, firebase or not, you need JS to make the web page dynamic.

#

It can't be achieved using Python only

stable kite
#

you can use firebase if you want it realtime
@stable kite, firebase or not, you need JS to make the web page dynamic.
@balmy stag thats for sure

balmy stag
#

But yeah you're right Firebase is a great idea

nimble epoch
#

you can use firebase if you want it realtime
@stable kite, firebase or not, you need JS to make the web page dynamic.
the answer got clear

#

i found something but not sure its Pusher, right?

digital hinge
#

@balmy stag Thats good idea. The log view from the Flask ap tho?

balmy stag
#

Yep !

digital hinge
#

havent got that working yet. running to a ```py
return codecs.lookup(encoding).name == "ascii"
TypeError: lookup() argument must be str, not function

lavish prismBOT
#

Hey @digital hinge!

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

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

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

https://paste.pythondiscord.com

digital hinge
#

Starting to think a progress bar with the popup message is a better idea for now...

nimble epoch
#

yep wish you luck

digital hinge
#

until i find the time to learn firebase and update on JS skillset

balmy stag
#

I'm getting invested in your problem ๐Ÿ˜†, I could try to build something in a few hours and show you my ideas in a few hours (need to work right now)

digital hinge
#

I am interested @balmy stag

#

ill experiment with a progress bar for now while the function loads

#

may be simple

balmy stag
#

๐Ÿ‘

digital hinge
#

if i know how to add this to my function in the Flask app this may be a solution: ```py
@app.route('/yield')
def index():
def inner():
for x in range(100):
time.sleep(1)
yield '%s<br/>\n' % x
env = Environment(loader=FileSystemLoader('templates'))
tmpl = env.get_template('result.html')
return flask.Response(tmpl.generate(result=inner()))

upbeat imp
#

So this question is more a web question than a python question, but maybe you guys have an answer to it. Anyways, so this script running on my python flask server runs the function updateLiveData() much more frequent than once a second, more like every 200ms or so, why is this?

window.addEventListener('load', function()
{
    var xhr = null;

    getXmlHttpRequestObject = function()
    {
        if(!xhr)
        {               
            // Create a new XMLHttpRequest object 
            xhr = new XMLHttpRequest();
        }
        return xhr;
    };

    updateLiveData = function()
    {
        var now = new Date();
        // Date string is appended as a query with live data 
        // for not to use the cached version 
        var url = "{{ url_for('static', filename='log.txt') }}" + "?" + now.getTime();
        xhr = getXmlHttpRequestObject();
        xhr.onreadystatechange = evenHandler;
        // asynchronous requests
        xhr.open("GET", url, true);
        // Send the request over the network
        xhr.send(null);
    };

    updateLiveData();

    function evenHandler()
    {
        // Check response is ready or not
        if(xhr.readyState == 4 && xhr.status == 200)
        {
            dataDiv = document.getElementById('log');
            // Set current data text
            dataDiv.innerHTML = xhr.responseText;
            // Update the live data every 1 sec
            setTimeout(updateLiveData(), 1000);
        }
    }
});
</script>```
stable kite
#

@upbeat imp this run because you have used setTimeout()

upbeat imp
#

Yes, but not every second, its much faster. Like every 100ms or 200ms

stable kite
#

@upbeat imp because 1000=1sec

upbeat imp
#

But mine runs faster

stable kite
#

no it should not run faster

upbeat imp
#

Changing the value inside setTimeout() does nothing to the delay, even a value of 200000 is same speed

stable kite
#

@upbeat imp just get all functions out of eventlistner ()

upbeat imp
#

How would this work then?
xhr.onreadystatechange = eventHandler;

#

What triggers it

stable kite
#

i think you should first sent the request &then you should wait for response

upbeat imp
#

You have example?

stable kite
upbeat imp
#

hmm, im clueless

#

Oh well

#

It works i guess, just hogs alot of resources

devout coral
#

@upbeat imp are you simply trying to add some sleep to your code? Sorry. I was not following the conversation in its entirety.

toxic flame
#

Use vue and django together!

upbeat imp
#

@upbeat imp are you simply trying to add some sleep to your code? Sorry. I was not following the conversation in its entirety.
@devout coral Hmm yeah sort of

#

updateLiveData runs to fast

#

setTimeout does nothing it seems

#

Well, it does call the function i guess, but not with a timeout

devout coral
#

Well, I think it does call with a timeout I think it is calling itself...

#

Have you tried user setInterval() and taking it out of the function?

#

Have set interval set to 1 second and set it to your function.

upbeat imp
#

I will try

#

It only does the GET request once if i put setInterval outside the eventHandler

#

Which makes sense, since there is no loop

devout coral
#

Well, no setInterval is suppose to call the function every time on a set interval.

#

As opposed to setTineout which only calls it once

upbeat imp
#

Did you mean outside the window.addEventListener function?

#

After this JS session, i will never complain about doing work in C again ๐Ÿฅฒ ๐Ÿ˜‚

devout coral
#

Yes

upbeat imp
#

hmm

#

No it only runs it once

#

I don't know how scope works in JS, but the setInterval is maybe outside the scope for the function its calling?

devout coral
#

Let me see what you did.

upbeat imp
#

It does fetch the log.txt once on page load

#

but not every second

devout coral
#

Put the set interval inside of the onload event like where the function call is.

upbeat imp
#

Does js have a "dumb" delay? That does not require any functions call as parameter?

#

well fuck me

#

lol

#

uhm

faint umbra
#

So i have djangorestframework installed in my folder and it is also in the Pipfile but when i add 'rest_framework' in my SETTINGS of settings.py i get the error saying 'No module called rest_framework' found

upbeat imp
#

So this worked

setTimeout(function(){
   updateLiveData()
}, 1000);
faint umbra
upbeat imp
#

How does that differ from this?

faint umbra
#

Set Timeout is used to add some delay in code

#

you need a function in it

#

it wont work without function

upbeat imp
#

Se the post above

#

I did insert a function

faint umbra
#

nope.. the function didnt have the {} at the end

#

you need to do updateLiveData = function(){}

near bison
#

I have to work on a complex project (complex from my level). How would i start ? like how do i plan what goes where and the database structure and stuff. i have a lot of time

upbeat imp
#

It is a defined function further up in my code

faint umbra
#

ah well i got no idea then sorry

#

I have to work on a complex project (complex from my level). How would i start ? like how do i plan what goes where and the database structure and stuff. i have a lot of time
@near bison watch some tutorials and try to understand stuff before you move on to other stuff.. that shud do it ๐Ÿ˜„

near bison
#

how do i plan a project

#

how do i choose what stack to use

faint umbra
#

that is up to you and what you are more experienced with and more comfortable with and this is a not a question to be asked in here

#

So i have djangorestframework installed in my folder and it is also in the Pipfile but when i add 'rest_framework' in my SETTINGS of settings.py i get the error saying 'No module called rest_framework' found

covert pulsar
#

do you use Docker or venv?

cold haven
#

hi i'm back

#

you can't just use venv

#

you need both docker and venv I believe.

#

they both have their uses.

near bison
#

How are big projects actually planned by professionals?

cold haven
#

You could use venv, but it's easier to create a docker container for making a cfg backup, and connecting your service to a DB.

#

After using venv

stable kite
quick cargo
#

I wouldnt compare Docker to a Venv

cold haven
#

I believe there are additional steps that you must take if you don't want to use docker.

quick cargo
#

Or use them the same

#

Venv's are useful for just organising multiple projects keeping dependancies seperate

#

Docker covers alot more than Venvs do

cold haven
#

yeah, it basically just builds a local virtual environment.

stable kite
#

How are big projects actually planned by professionals?
@near bison wdym?

quick cargo
#

No one should deploy their stuff by just using a standard python venv and a basic shell script

#

and if you do that you really aught to rethink

cold haven
#

I agree.

near bison
#

@stable kite Like before you actually go into the programming part. you have to make a map of what goes where . right?

cold haven
#

docker is what's used outside of a virtual env.

quick cargo
#

its a container system

#

so... ALOT

cold haven
#

you need to set up environmental variables

stable kite
#

@near bison right

quick cargo
#

As a perfect example -> One of my Servers went down unexpectantly and came back up 20 minutes later, Docker auto starts and sets up everything automatically without me touching anything

near bison
#

@near bison right
@stable kite How is that actually done in production?

quick cargo
#

you can limit system resources, manage network etc....

#

manage os types

cold haven
#

In a virtual environment, you have to run a cmd to start the server, where docker would set up your DB and your service on a Server in the same manner by running a script.

covert pulsar
#

is it true docker requires a lot of ram for db?

quick cargo
#

no?

#

where df did you hear that lmao

covert pulsar
#

one my friend said

stable kite
#

@near bison I think they have some idea & just start it & then think how to implement the part

cold haven
#

docker is simply a script that runs in the OS.

quick cargo
#

the DB will use the same amount of Ram as it would normally At least it wont use any noticeable amount more

#

Docker is alot more than a script

#

alot more

near bison
#

@near bison I think they have some idea & just start it & then think how to implement the part
@stable kite LOL. really ?

cold haven
#

ok sure

covert pulsar
#

yeah it's a working linux image

near bison
#

people just start coding when they make a website ?

cold haven
#

you could easily say that it is a script in a general sense, would you like to add something that it is? ๐Ÿ™‚

near bison
#

you need have a plan right?

quick cargo
#

Process manager
Server Daemon
Executable
Container manager

would probably all go before i use the word 'script' for docker lol

faint umbra
#

So i have djangorestframework installed in my folder and it is also in the Pipfile but when i add 'rest_framework' in my SETTINGS of settings.py i get the error saying 'No module called rest_framework' found

quick cargo
#

@near bison depends what it is

covert pulsar
#

@faint umbra do you use docker?

faint umbra
#

no

stable kite
#

@near bison yes

quick cargo
#

Large companies usually have seperate teams of Designers, developers etc...

faint umbra
#

i used pipenv

#

and pip3 too tried both

cold haven
#

or you could shorten it to a microservice.

covert pulsar
#

@faint umbra try using venv, it always works as for me

cold haven
#

whatever you think is faster.

faint umbra
#

i am following a tutorial

#

how can i use venv?

cold haven
#

that covers it all that you mentioned

quick cargo
#

Another reason i like docker -> No BS of command line linux python confusion

covert pulsar
#

how can i use venv?
@faint umbra python3 -m venv <name_of_env>

#

and do source /venv/bin/activate to activate venv

faint umbra
#

uh ok

#

i am on windows

#

so source isnt a thing for me

quick cargo
#

then its "./venv/scripts/activate.bat"

faint umbra
#

ah ok ty

covert pulsar
#

yeah

near bison
#

I need to build a website for a business. it needs like the basic information and stuff. the additional features needed are

  1. Inventory Management - They will update their inventory and clients can know how much they can order
  2. List of all their products
  3. Clients should be able to order products and pay online if they want . which can be sometime large amounts
  4. App should be available in multiple languages
  5. Clients can inform business about their requirements
faint umbra
near bison
#

THis is the project basicall

#

I don't know how i would plan this. how the db should look and how i would host it

#

i was hoping to get some help here

faint umbra
#

Did you get a job for a real business?

covert pulsar
#

@faint umbra what shell do you use?

faint umbra
#

@faint umbra what shell do you use?
@covert pulsar powershell

near bison
#

@quick cargo

cold haven
#

@near bison ok

near bison
#

How do i move ? what stack would i choose ?

covert pulsar
#

@faint umbra try using some other path, but there this script should be

near bison
#

how would i plan it and how the db should look like and the tests

quick cargo
#

ehh sounds like something Django would fit reasonably into if it doesnt need to be massively performant per proc

#

multiple languages is hard no matter what you do but can just be different html files or what ever

near bison
#

django lacks performance?

quick cargo
#

Django slowwwwwwwwwwwwwwwwwwwwwwwwwwwwww

near bison
#

damn

cold haven
#

I am new to Django, but have heard great things about it. I think stacks are moving more towards python in the future as well.

near bison
#

what would be a faster alternative ?

covert pulsar
#

but it has everything in the box

quick cargo
#

For payment Stripe is a pretty good api or Paypal but that depends

#

do you actually need that performance though

cold haven
#

probably not for small to mid sized apps

near bison
#

i don't know how much difference it makes

#

this is a small app right?

#

or a medium one?

quick cargo
#

probably

#

I wouldnt say medium

cold haven
#

B2C probably

quick cargo
#

pretty standard E-Commerce setup from what ive gathered

near bison
#

I am planning to learn by doing this

#

so i don't wanna mess up

cold haven
#

yeah, I don't know how they would update info in a database though when they get it. I think you need a database administrator for that sort of thing anyways.

quick cargo
#

if you're learning i can garentee you'll mess up

#

even if you're not learning you'll probably mess up at some point

near bison
#

django has an inbuild admin panel @cold haven

quick cargo
#

its not a bad thing

#

you'll only learn by your mistakes

covert pulsar
#

also inbuild templates

cold haven
#

doesn't it fall somewhere in-between data warehousing?

near bison
#

i was hoping to get help from you guys through out

cold haven
#

I think it would

near bison
#

I think the default django admin panel would work for me

quick cargo
#

stripe is supposed to be fairly easy to use for payments api wise

#

Django would probably be a good fit for you

cold haven
#

what is Django admin panel? a preset template?

near bison
#

i haven't done all these stuff. but i have a lot of time to get this done

quick cargo
#

@cold haven arent you learning Django rn?

cold haven
#

yes

quick cargo
#

Have you never came across the admin panel before?

cold haven
#

to answer your question, no. I have seen it in other frameworks and CMS

near bison
#

what is Django admin panel? a preset template?
@cold haven Yes kinda, you can view , edit and add new entries to the db

cold haven
#

kind of like phpmyadmin?

quick cargo
#

run what ever project you're making

#

and go to http://your:host/admin

near bison
#

to make it work in different languages will i have to redo the templates in those languages ?

quick cargo
#

diffrent programming languages?

near bison
#

nope

cold haven
#

did you read my question really quick?

near bison
#

website content languange

cold haven
#

anyone know of phpmyadmin and if it's similar to that of Django Admin panel?

near bison
#

like english, french etc

quick cargo
#

sorta but not quite

#

its not as complete

#

idek how you havent came across that

#

cuz the ORM practically forces you to when you setup a project with the super user

near bison
#

anyone know of phpmyadmin and if it's similar to that of Django Admin panel?
@cold haven Compare to phpmyadmin django admin panel has a lot of {your_name} involved

cold haven
#

anyways, I still think it falls under category of DB admin

#

or data warehousing of sorts

quick cargo
#

sorta

#

Bit of a bitch to customise

near bison
#

yea , ig

#

how would i plan my current project ?

cold haven
#

i don't think a normal manager can operate it that doesn't have knowledge in that field.

quick cargo
#

they could easily manage it

#

EASILY

#

the admin page is dead easy to use and very hard to get wrong without deliberately doing it wrong

cold haven
#

I said if they don't have any knowledge in computers at all, and I'm talking at the microsoft excel level.

quick cargo
#

yeah

#

trust me ik of your 'normal manager' level

cold haven
#

so it has a user-friendly UI

#

something that you can plug values into easily without knowing what a row or a column is

#

?

quick cargo
#

theres a bit less than normal cuz im logged in as a reduced permissions user

cold haven
#

yeah that's nice

near bison
#

You have Users + Groups extra if you are a superuser

quick cargo
cold haven
#

and you can set it to add blobs or img

quick cargo
#

you can do alot with it

#

just a bit awkward to customise the style but most people dont care about that

near bison
#

how do i make the website in different languages (people language)? do i need to have a different template for each language?

cold haven
#

A company would probably want their own software because it is unlicensed.

quick cargo
#

probably the easiest method

#

i refuse todo multi language stuff after the hell of previous usage with it

near bison
#

and how can i add a chat feature to it?

cold haven
#

you want to make it look really good for a company, and especially if it is customized for a specific company.

#

you want it to look good.

quick cargo
#

i would probably do one thing first

#

worry about the chat later

near bison
#
  • if you don't mind can you tell me a bit about the hosting part ? do i need to use aws (or some other clound plat)?
quick cargo
#

otherwise you're probably gonna overthink stuff while learning a system thats probably gonna be new to you

#

you dont need to use aws no

cold haven
#

I have used aws before.

quick cargo
#

Django is a WSGI framework

cold haven
#

it's nice

quick cargo
#

so will run on any WSGI webserver e.g. Gunicorn which can run on any VPS etc...

near bison
#

so ?

stable kite
#

@near bison you can use pythonanywhere,heroku

quick cargo
#

Free hosts are very limiting though to add to that

near bison
#

what is downside in using aws ?

quick cargo
#

Err cost

near bison
#

does it cost more

#

oh

quick cargo
#

Serverless can cost a shit ton if you fuck up your scaling

cold haven
#

You definitely want to set it up on a cloud service, that way you don't have to worry about implementing the security yourself. You can just use Encryption as a service.

sly echo
#

I am a complete beginner and I want to be a pro Django and Flash coder.
How and where to start?

quick cargo
#

Serverless's advantage is that you pay for what you use rather than a normal vps or Dedi that you pay monthly

near bison
#

do you think heroku will work for me ? for the current senario ?

#

You definitely want to set it up on a cloud service, that way you don't have to worry about implementing the security yourself. You can just use Encryption as a service.
@cold haven you mean ssl ?

cold haven
#

yes

quick cargo
#

however, if you setup stuff up wrong or use more than you expect you can quite easily spend more than you would on a monthly thing

sly echo
#

anyone?

quick cargo
#

You should know how to setup SSL anyway

#

that is a massive thing, dont rely on someone else doing it for you

#

@sly echo the Django tutorial

near bison
#

i can just watch a tutorial for the ssl stuff right ?

quick cargo
#

its not hard

cold haven
#

Cloud has just about everything. You can set up a devops pipeline, backups, security, and DNS reporting.

sly echo
#

I see.
Can you send me a link to the tutorial?

near bison
#

would heroku work for me

quick cargo
#

you need a SSL key and cert set from somewhere (Cloud flare do it for free) and then give gunicorn the SSL cert and key paths

#

err probably not

cold haven
#

you are going to want to have a backup which is probably important for any organization.

quick cargo
#

you can but its a pretty bad idea

near bison
#

what would be the right choice for me

sly echo
#

I need some help in a program.
Could you help me?

#

Thanks!

quick cargo
#

@near bison i would worry about starting first

#

hosting is the last part of it

cold haven
#

it depends if you are running linux or windows.

sly echo
#

A useful application for a dictionary is to remember, or cache,
previously obtained results so that they can be retrieved from the cache
when they are requested a new. Write a program so that the user can
repeatedly enter file names. If the user enters the same filename
more than once, look up the answer from a dictionary instead of
counting the words again.

cold haven
#

you may want to go with azure if it's windows

sly echo
#

@quick cargo could you help me with this?

quick cargo
near bison
#

A useful application for a dictionary is to remember, or cache,
previously obtained results so that they can be retrieved from the cache
when they are requested a new. Write a program so that the user can
repeatedly enter file names. If the user enters the same filename
more than once, look up the answer from a dictionary instead of
counting the words again.
@sly echo a set would work too

tame kelp
#

uh can someone help with a small prob?

#

wsforms.validators doesnt have Email validation built in?

quick cargo
#

use regex

near bison
#

just install it

quick cargo
#

or install it yh

tame kelp
#

pip install email_validator ?

near bison
#

pip install wtforms[email] should do it @tame kelp

tame kelp
#

alr

sly echo
#

@near bison
could you write the program for me so I can look and understand it better?

near bison
#

with a dictionary or a set ?

tame kelp
quick cargo
#

need to instantiate it

sly echo
#

I am weak with both.
can you do in the dictionary first?
@near bison

quick cargo
#

-> () call it

tame kelp
#

oh

#

oh yeah mb

#

k works ๐Ÿ‘

#

also, you were saying i can use regex, but how do i apply my own conditions to my fields?

near bison
#
cache = dict()

while True:
    filename = input("Enter a filename")
    if filename in cache:
        print("That was already entered")
    else:
        cache[filename] = 'Seen' # OR something else 
        print("That wasn't found in the cache")
``` @sly echo set would have been a better way
sly echo
#

I see.
Can you show with set?

near bison
#
cache = set()

while True:
    filename = input("Enter a filename")
    if filename in cache:
        print("That was already entered")
    else:
        cache.add(filename)
        print("That wasn't found in the cache")
sly echo
#

Thanks man

near bison
#

@quick cargo Do you guys follow a test first approach ?

quick cargo
#

wdym by that

native tide
#

probably means unit tests

quick cargo
#

oh then yes test the shit outa it

native tide
#

you use a framework for it? or just manual

quick cargo
#

though i admit im pretty bad using unit test itself

#

if i do tests i normally test individual things making a file that houses the test

sly echo
#

@near bison
Thanks a lot.

quick cargo
#

i have a file that auto runs the tests then when i update stuff

sly echo
#

Just one more help

#

function that takes in a string, removes the duplicating letters from the list and returns the new string. The first occurrence of the letter should not be removed.

native tide
#

what do you test though...

sly echo
#

Is it done with .split?

quick cargo
#

well recently when its been with my framework Everything

#

The URL compiler that turns the placeholder strings into regex runs though every single possible combination of patterns with the pre made converters and and random set of filler strings

sly echo
#

@near bison

native tide
#

@sly echo you can do that with a for loop...

sly echo
#

a='aboo'
def removeDupWithoutOrder(a):

return "".join(set(a))

print (removeDupWithoutOrder(list(a)))

#

I cannot go ahead of it

#

I am really bad at it.
I feel so sad.
I want to become a pro python coder and I cant even solve such questions.

torpid terrace
#

@sly echo sets are unordered, so while that's a good idea, it won't always give you the correct result.

#

And strings are iterable, so you can iterate through each character in the string with a for loop, ie:
for char in a:

near bison
#
string = "aaabbbccccd"
seen = set()
newString = ""
for letter in string:
    if letter not in seen:
        seen.add(letter)
        newString += letter
print(newString)

This would work , right ?

whole sierra
#

I am trying to only display my searched results post search. How exactly would I achieve this?

near bison
#

what is the issue now?

#

what variable holds the results ?

whole sierra
#

q

nova shadow
#

Can someone help me with JavaScript and Jinja2? When I add Jinja inside a script tag, it throws a lot of errors but runs fine

bronze oak
#

Hey guys, I am new to django, just completed the polling application from the django documentation. Can you suggest where should start from?

near bison
#

q
@whole sierra huh , it should be client_info right? that's what you are looping over

whole sierra
#

yes

#

wait

#

q holds the query

#

and i only want loop results after q is defined

near bison
#

if q

#

Can someone help me with JavaScript and Jinja2? When I add Jinja inside a script tag, it throws a lot of errors but runs fine
@nova shadow That's because they are not valid js syntaax

whole sierra
#

doesnt work :/

nova shadow
#

Yeah, but is there anyway to hide those errors?

near bison
#

doesnt work :/
@whole sierra try if client_info

nova shadow
#

or should I just leave it?

whole sierra
#

:/ same result

#

so confused

near bison
#

Yeah, but is there anyway to hide those errors?
@nova shadow idk, there should be a vscode specific way to not show some errors, i am sure though, i don't even know even this is how you should achieve what you want, i haven't seen jinja templates editing js

whole sierra
#

ugh!! finally fixed it

#

if query!

#

appreciate your time!

nova shadow
#

alright thank you

nimble epoch
#

Hello, is any differences between flask_security and flask_login. im using flask_login should i change it to flask_security?

sly echo
#
string = "aaabbbccccd"
seen = set()
newString = ""
for letter in string:
    if letter not in seen:
        seen.add(letter)
        newString += letter
print(newString)

This would work , right ?
@near bison not working

near bison
#

What part ?

sly echo
#

function that takes in a string, removes the duplicating letters from the list and returns the new string. The first occurrence of the letter should not be removed.

near bison
#

Just wrap this inside a function

sly echo
#

if I take the input as "Khaan"
It should return [Khan]

#

first occurrence of the alphabet in a string should remain

#

and the result should be in list

near bison
#

return [string]

sly echo
#

def RumDep():
string = "aaabbbccccd"
seen = set()
newString = ""
for letter in string:
if letter not in seen:
seen.add(letter)
newString += letter
print([newString])

#

@near bison

near bison
#

Take string as a param

#

And return the final thing

#

def RumDep(string):
seen = set()
newString = ""
for letter in string:
if letter not in seen:
seen.add(letter)
newString += letter
return [newString]
@sly echo

#

Damn, i am on my phone, it's hard to edit

sly echo
#

works now
thanks

peak forum
#

I'm working on a portable browser experience using pyppeteer/headless chrome. Wondering if anyone could point me towards a pattern example for implementing CSS.takeComputedStyleUpdates & CSS.trackComputedStyleUpdates from ChromeDevTools API.

Seems like it would be much more efficient way for me to get computed styles but I'm having trouble grokking it.
https://chromedevtools.github.io/devtools-protocol/tot/CSS/#method-takeComputedStyleUpdates

static harbor
#
roles=EmployeeRoleMap.objects.filter(empId=emp).order_by("-startDate")[0]

how to access all roles field?
I am trying roles.values("id","name")
doesn't work

late gale
#

here is my forms .py

from django import forms
from django.contrib.auth.models import User 
from django.contrib.auth.forms import UserCreationForm
from .models import Profile

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()
    class Meta:
        model = User
        fields = ['username', 'email','password1', 'password2']


# USER UPDATE FORM!!
class UserUpdateForm(forms.ModelForm):
    email = forms.EmailField()
    class Meta:
        model = User
        fields = ['username', 'email']

#PROFILE UPDATE FORM
class ProfileUpdateForm(forms.ModelForm):
    Committees = (
        ('IT','IT'),
        ('Design','Design'),
        ('ER','ER'),
        ('Design','Design'),
        ('Marketing','Marketing'),
        ('Coaching','Coaching'),
        ('Media','Media'),
        ('Branding','Branding'),
    )
    committee = forms.ChoiceField(choices=Committees, required=False)    


    class Meta:
        model = Profile
        fields = ['bio', 'image', 'position' ,'committee', 'achievement','awards', 'experience']
#

and here is my models.py

from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete= models.CASCADE)

    bio = models.TextField(max_length=300)

    Committees = (
        ('IT','IT'),
        ('Design','Design'),
        ('ER','ER'),
        ('Design','Design'),
        ('Marketing','Marketing'),
        ('Coaching','Coaching'),
        ('Media','Media'),
        ('Branding','Branding'),
    )
    committee = models.CharField(choices=Committees, max_length=10, default='')

    position_list = (
        ('Member', 'Member'),
        ('Head', 'Head'),
        ('Vice', 'Vice'),
        ('President', 'President'),
    )
    position = models.CharField(choices=position_list, max_length=10, default='Member')

    awards = models.TextField(max_length=300, null= True)

    experience = models.TextField(max_length=300, null=True)

    achievement = models.TextField(max_length=300, null=True)
    

    image = models.ImageField(default='default.jpg', upload_to='profile_pics')

    def __str__(self):
        return f'{self.user.username} Profile'
        ```
#

please i just didnt do anything i was taking a look at the website again and found this error showed up

#

idk what is the wrong

#

please i really need help in this

#

and here is the template as well

neon quiver
#

Hi, I would like to contribute to some open source projects, can you recommend any for first time Python contributors? thinkmon py_strong ๐Ÿ˜€

void parrot
#

hello

#

i need help

native tide
#

with what

cold socket
#

Does Gunicorn expect your Flask application to follow a specific file structure like the Factories or Blueprint structures?

quick cargo
#

no

#

it doesnt care about that

#

it only imports the specified target file and get the what ever the variable that contains Flask() instance

cold socket
#

For some reason Gunicorn seems to error out on my imports

#

But when I run flask locally without Gunicorn the app runs fine

broken abyss
#

should I create separate app for authentication in Django?

#

what is best practice

acoustic oyster
#

I usually combine authentication with a "users" app. Not totally sure on best practice though.

broken abyss
#

user app?

#

u mean registration?

quick cargo
#

@cold socket most likely because of the CWD you're running the app in

dense slate
#

"app" is probably just a user folder that is registered in the settings.py.

toxic flame
#

@broken abyss there is a built in django login/registration / auth system

rain ledge
#

Anyone ever displayed previews for PDFs/JPG/etc on a django template? I'm serving the file as an HttpReponse but it keeps auto-downloading rather than rendering in the browser

gaunt marlin
#

@rain ledge try serving the content as image instead:

return HttpResponse(image_data, content_type="image")
rain ledge
#

i'm mostly focused on PDFs to start, this is asking me how to save/open it

#

but i'm hoping that i can get browsers to just open PDFs in a new tab @gaunt marlin

gaunt marlin
#

oh ok you want to open in new tab

#

@rain ledge

return HttpResponse(file_data, content_type="application/pdf")
rain ledge
#
def read_pdf(filepath):
    pdf_temp_file = NamedTemporaryFile(delete=True)
    in_memory_pdf = r.get(filepath, stream=True)

    for block in in_memory_pdf.iter_content(1024 * 8):
        if not block:
            break

        pdf_temp_file.write(block)

    pdf_temp_file.flush()
    temp_file = files.File(pdf_temp_file, name="zd.pdf")

    return temp_file


def ticket_attachment(request):
    filepath = request.GET.get("filepath", None)
    content_type = request.GET.get("content_type", None)

    if content_type == "application/pdf":
        pdf = read_pdf(filepath)
        response = HttpResponse(pdf, content_type=content_type)
        return response
#

@gaunt marlin thoughts?

#

this still triggers an auto-download

gaunt marlin
#

@rain ledge that is on frontend part, to open new tab you would have an anchor link with target attribute

<a href="you_image_or_pdf_url" target="_blank">click here to open new tab</a>
#

you_image_or_pdf_url is url for your HttpResponse views

rain ledge
#
<a href="{% url 'view-
file'%}?filepath={{attachment.content_url}}&content_type={{attachment.content_type}}" target="_blank">{{ attachment.file_name }}</a>
#

@gaunt marlin feel like i'm going crazy on this one

steady owl
#

hey

#

uhhh

#

i suck doode

#

idk why im getting this error

#

everything here

#

i can only make shitty websites with html and css

#

๐Ÿ˜ฎ

rain ledge
#

@steady owl how are you attempting to run it?

gaunt marlin
#

@rain ledge your design on the url path is kinda wrong, here how i would do it:
urls.py:

path('image/<str:image_path>', views.my_image, name='api.my_image'),

views.py:

def my_image(request, image_path):
    # codes
    image_data = open(image_path, "rb").read()
    return HttpResponse(image_data, content_type="image")

and in your template:

<a href="{% url 'api.my_image' image_path=attachment.content_url %}" target="_blank">{{ attachment.file_name }}</a>

you can also implement like so with pdf file

steady owl
#

@steady owl how are you attempting to run it?
@rain ledge through the terminal

rain ledge
#

what is the command you're typing

steady owl
#

nothing

#

i just press the run button

#

says my template aint found

rain ledge
#

it can't be run as a single file like you're attempting

steady owl
#

bruh...

rain ledge
#

it's a package

steady owl
#

oh ok

#

got it working with debug

#

and changing the folder name lol

rain ledge
#

@gaunt marlin I passed them in as url parameters (?param1=param1&) because it's a full url to a third party website where i'm downloading stored files from. I'm downloading the file then serving it back.

#

i'm able to download the file, the problem i'm having is on the return, it auto-downloads rather than opened in the new-tab as expected

gaunt marlin
#

@rain ledge to confirm what causing it first, can you try adding a default image path in your code to see if it will download the image or open new tab?

#

because target="_blank" is how you open new tab

rain ledge
#

yeah, target="_blank" is in heavy use on the same template*

gaunt marlin
#

does it open new tab ?

#

just a working example for html

<a href="https://www.w3schools.com/howto/img_avatar.png" target="_blank">test</a>
rain ledge
#

yeah that opened

gaunt marlin
#
<a href="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf" target="_blank">test</a>
#

so it's working

rain ledge
#

that PDF auto-downloaded, the image opened

#

OMFG is this seriously a browser default setting

gaunt marlin
#

maybe

rain ledge
#

ug now it works. @gaunt marlin what's your venmo i'll buy you a coffee

gaunt marlin
#

_blank also based on your browser settings

#

haha it's fine glad i can help though ๐Ÿ˜„

rain ledge
#

๐Ÿ™ thank you

cold socket
#

@quick cargo @dense slate Actually the name of the file is called app.py

wispy ice
#

Has anyone worked with python and Tor? I need to have a server that receives a small .txt or some bytes, but i dont know if i need ftp, tcp...? Im so lost. Maybe someone knows any hints

#

Please tag me if you answer, ty

whole sierra
#

hello people

#

this is my url:

#

how can I grab the /65909865 from the href being passed??

#

all i need to that number ๐Ÿ™‚

glass blaze
#

request.GET.params

#

request.GET

whole sierra
glass blaze
#

def home_view(request, pk)

whole sierra
native tide
#

Hi

#

How can I not be forced to write all extending code in every template?

#

atm i write this in every page

{% extends 'base.html' %}

{% load static %}

{% block content %}

#

i love this just to be default behavior of all template files, unless i type something else

#

find a solution for static

#

'builtins': [
'django.templatetags.static',
],