#web-development

2 messages · Page 14 of 1

knotty lark
#

err theres a way in JS hold on

elfin trench
#

ok then take ur time

knotty lark
#

`

<a href="javascript:history.back()">Go Back</a>

`

#

try this

elfin trench
#

huh

#

it cant find my page

native tide
#

dude you gonna have to start googling lol

elfin trench
#

no but the problem is

#

the page i want to go to

#

is in the same folder

#

and visual studio code redirects to it also

inner forge
#

Hey guys, need some help with setting up Django. First and foremost, I must say that my user folder is in cyrillic and I'm trying to use Django 2.1.1

#

When I try to do python manage.py runserver it just gives me errors

#

And those errors are so odd, because at first it was giving me UnicodeDecodeError: 'utf-8' blahblahblah: invalid continuation byte

#

and now it gives me something else instead
ValueError: too many values to unpack (expected 2)
django.core.exceptions.ImproperlyConfigured: Passing a 3-tuple to include() is not supported. Pass a 2-tuple containing the list of patterns and app_name, and provide he namespace argument to include() instead.

inner forge
grand badge
#

show code mr darkness

inner forge
#

@nocturne plover yeah I figured it out later down the road

#

And ifex the invalid continuation byte issue too

#

Apparently I had to rename my PC, it was in cyrillic

raven harbor
#

@grand badge sure im doing that but just want to know how hard it is..

fast saddle
#

Hey, I had a question about saving tokens. I'm creating a web dashboard for my Discord Bot and I was wondering what the best way was for caching a token that is used for OAuth2 so that the site knows what to display based off of the token (e.g. know to display which user's servers). My current (unsafe and private) way is to put the user's access token in the url, but i'm sure there are safer ways to do things like that. I am using Python Flask for this dashboard.
I've done a bit of research and learned that this topic may be relating to cookies or databases

versed lotus
#

in the case of flask, you could store it in the session. You have to set the "SECRET_KEY" option to use sessions

queen needle
#

The module Flask-Security has a lot of boilerplate options if you need an all-round solution for authentication

#

Otherwise just use Flask-Session

#

Store the session id in a cookie and you keep the actual data in a server side session

#

You can store the session data in a backend like memcached if you're expecting a lot of traffic

chilly hearth
#

Are there any good crash courses or tutorials out there for Flask? I feel like I'm uneducated on how I would implement sessioning and tokens within Flask. Plus, I've heard a bunch of packages like Celery, RabbitMQ and others get thrown around and I'm not sure the use cases behind them and whether or not I'd even need them.

meager anchor
#

Celery is a task queue, rmq a message broker, those don't have a lot to do with sessions in itself

chilly hearth
#

Thanks, I'll check it out, it's been a minute since I've worked in Flask.

chilly hearth
#

@meager anchor Do you know of any good production level Flask projects I could read through to see some good practices?

meager anchor
chilly hearth
#

Sweet! Thanks, I'm still trying to figure out where to start, but that gives me an idea of what a finished product looks like.

meager orchid
#

Good evening here I am developing a web radio in Django, I am confronted with a problem that of streaming what is the advice you can give me if there is an existing middleware that can help me thank you

raven harbor
#

My js file for water repellent is not working in python html . But in normal html it works

#

What may be the reason?

#

Is there any code to include for js file in python

meager anchor
#

no that's not how it works

#

what exactly are you trying to achieve

native tide
#

Hey guys.. learning flask.. made my first relational db , tables : user and profile where profile is related to user, my question is:
isn't it supposed to automatically add an entry in profile when I insert in user?

knotty lark
#

Errr that's vague but no

#

Even if two tables define a relationship you have to add the data

native tide
#

thanks shawn this helps a lot.. any advice on how to achieve this ?

deep cave
#

just.. add the data to both.

native tide
#

Will do.

raven harbor
#

@meager anchor im trying to add water repelent effect throughout my website in everypage is it possible??

meager anchor
#

computers can do anything if you work at it hard enough

rigid stratus
#

true that

#

i remember my dad telling me that when i was a kiddo and i really could not believe him, funny to think about today

raven harbor
#

@meager anchor thanks im working on it with my knowledge

#

@rigid stratus lol

#

@meager anchor can i send the code co u can get wt im trying

meager anchor
#

you can send it to me but I don't know anything about frontend so I'm not sure what I would do with it

raven harbor
#

its completely fine , u can tell me weather uv seen something like this used in webpages

raven harbor
rigid stratus
#

you're welcome

raven harbor
#

wow thanks a lot @rigid stratus

#

can i use this on my website is it possible?

rigid stratus
#

toook me 10 sec np

#

ofc

#

its easy as it can be

raven harbor
#

im just started so this mean the world for me

#

i can bring this effect in a seperate html page but in my main html where i have all my code in its not working

rigid stratus
#

move shit around

#

see why all of em work and one doesnt

#

thats how u learn

raven harbor
#

finger_gun_dank ill make it soon

#

please tell me its possible in this page or not ill start working

rigid stratus
#

look at the source code

#

see how he did it

#

and also look at the console etc

#

all very helpful

autumn flare
#

Is that a good deal for $15?

deep cave
#

the bandwidth cap would be a dealbreaker for me.

#

but depends on the specs of the server.

autumn flare
#

Alright, I've asked for another package, I'll see what else there is.

#

I think there's an unlimited package

#

@deep cave Did I mention it's a one time charge? xD

deep cave
#

wat.

autumn flare
#

I know a guy

deep cave
#

any server in the world is worth 15 bucks one time charge.

autumn flare
#

Ah

#

Thought usual ones were like monthly

deep cave
#

yes.

#

I pay between 5 and 30 bucks a month for all of mine.

autumn flare
#

Yeah this one from the guy I know, one time lifetime charge, aka no monthly or yearly charges, pay once and you're done

#

I think the unlimited package was $20 or $25

autumn flare
#

I bought it 😃

deep cave
#

good stuff

autumn flare
#

yeah got it for a one time charge, and it's for a life time 😃

#

got it for $15

#

pretty kind guy

#

can hook you up with him if you want to

#

just let me know

golden ferry
#

@autumn flare I'm interested. Cause that's a hot deal

autumn flare
#

@golden ferry Sure I'll check with him! And yeah, it's an insanely amazing deal...

olive wharf
#

@autumn flare * winks intensely at User *

tame viper
#

stares loudly

autumn flare
#

😅

#

Just DM me whoever is interested and I'll see if I can hook you all up

digital bluff
#

oh its a webserver

#

ehh

autumn flare
#

@digital bluff yeah with these:

#
Unlimited Disk Usage
Unlimited MySQL® Disk Usage
Unlimited Bandwidth
Unlimited Addon Domains
Unlimited Subdomains
Unlimited Aliases
Unlimited Email Accounts
Unlimited Mailing Lists
Unlimited Autoresponders
Unlimited Forwarders
Unlimited Email Filters
Unlimited FTP Accounts
Unlimited MySQL® Databases```
#

Though he has some other packages as well & can make custom ones (he's an admin)

digital bluff
#

yeaaaaa, but i kinda want to run jenkins and openvpn and hastebin and a bot

autumn flare
#

@digital bluff Yeah, as long as it is legal you're good

digital bluff
#

but its a webserver

#

how do i install/manage those services?

#

does it allow ssh access?

autumn flare
#

yeah it allows ssh

deep cave
#

no soliciting in this channel. this ends now. if anyone needs a server, use a trusted webhost not some guy on discords friends server who is an admin.

autumn flare
#

It's installed in cPanel already

digital bluff
#

@deep cave uhhh

#

hi

autumn flare
#

@deep cave Yeah it kinda went overboard when I tried to hit you up and everyone got interested 😅

deep cave
#

how do I know you're not the friend and that this is how you get people to paypal you 20 bucks.

autumn flare
#

🤔

#

I guess you don't.. I mean not really sure how I could prove it unless I hook you up with him but then again it's the internet and you could claim it's me using multiple accounts or something

deep cave
#

anyway let's just get this channel back to what it's about, which is helping people with webdev questions.

digital bluff
#

well generally you would get some more info before you pay him

autumn flare
#

I guess he could hook you up with demo or something, idk, just dm me, it ends now anyway as @zinc cypress said.

#

oops, wrong lemon.

marsh canopy
#

Hey, I need some help with python flask: I want to have an input that user would enter a number and when he would press submit or sth it would redirect him to /asdf/<number> where <number> is what he entered. Is that possible?

knotty lark
#

Yes it's possible, but you could do that all client side if you don't need to process anything

marsh canopy
#

yeah, it can be client side, no problem w/ that

knotty lark
#

Then you can simply have an input box and a button with an onclick event that redirects the user to the desired url, using the value of the textbox as part of the url

olive wharf
#

Watch so it doesn't allow them to direct to any directory you didnt intend for though

marsh canopy
#

@knotty lark how exactly would I do that? I am not that fammiliar w/ HTML so any help/resources would be appreciated.

quiet solstice
#

The jabascript location API

knotty lark
#
<input type="text" id="userinput"/>
<button onclick="gotolink">Go</button>
function gotolink(){
  let where = document.getElementById('userinput').value;
  location.href = "baseurlhere/"+where
}
#

that might not work, I didn't try it and I haven't done JS in a while

#

but that's the gist of it

#

you're gonna want to do some validation ideally

quiet solstice
#

that doesn't work on older browsers

olive wharf
#

You sure you wanna do it client side?

knotty lark
#

Yeah ideally this seems like something that would benefit from some server side validation

quiet solstice
#

Does it matter if people can just go to all the numbers?

olive wharf
#

I'm not completely sure how permissions and etc work if it's a script directing you

marsh canopy
#

I can go SS as well. In the beginning I was thinking of going with Flasks url_for("/asdf/" + number) if that would be possible

olive wharf
#

but what if ../admin was passed

quiet solstice
#

@olive wharf it's like a normal get request

knotty lark
#

I mean that's not a security problem about the redirect script

#

it's server side permissions that are fudged

olive wharf
#

In that case I suppose it's safer than i estimated

#

Nontheless keep it in mind :P

marsh canopy
#

currently I have tried @knotty lark 's solution, but when I click Go nothing happens. Could it be the fact that I have put only the /asdf/ instead of baseurlhere?

#

is there a way to fix that?

knotty lark
#

As I said, my JS is rusty, you might have to fix the onclick handler function or something : )

#

Well my client side JS anyways

marsh canopy
#

is there an easier way to do this Server Side?

#

Ok, I think I got something:

In my HTML I put this:

<form method="POST">
        <input name="goto">
        <input type="submit">
    </form>

And I have added this snippet of code to my .py file:

@app.route('/', methods=["POST"])
@app.route('/index', methods=["POST"])
def index_post():
    return url_for("asdf/" + request.form["goto"])

But that last part throws an error, saying: can't build url for endpoint ...
Also, my asdf is defined as such:

@app.route("/asdf/<device_id>")
def asdf(device_id):
    ...
#

How could I get around this?

#

Nevermind, I have to do this: url_for("asdf", device_id=request.form["goto"])

#

also redirect()

#

Thanks for the help anyways!

rose shuttle
#

Hello, I've done a live Python course, was about 50 hours, learned the basics and a bit more, went for a few tutorials on django as well, learned a bit, created a website with a blog app, all good, but my issue now is that I have a target project, but don't know how to actually start, and I know if by any chance, any django expert would have 15-20 minutes time for a short chat, not to help me write the code, but to show me a few paths on where I should head to, and maybe give a few tips on how my general plan should look like, of course, if this request is what people normally would ask for, if not, well anything helps, as google did for a while.
Thanks a lot!

wintry raven
#

What beginner Django tutorials do you guys recommend? I've used php all my life and want to get into Python for backend development.

tame viper
#

@wintry raven

ornate coral
#

i have copied this from another channel where I incorrectly posted:

#

I have a confusing architecture question. Could you please help me find an answer? I am using Django and I have a long running Scrapy task. Ideally, on a page, a user would press the start button and the Scrapy task would start, and a loading icon would show. Let's say the Scrapy task would take hours to run. I think this is stateful because the user could navigate away from the page and return and if the task is still running then the loading icon should show. So do you think I should use React for the front end?
Also whether or not I use React, how do I listen for when the Scrapy task is finished so I know to remove the loading icon on the page? Should the front end poll the backend every x seconds?
I am planning on using django rest framework regardless because it sounds like the easiest way to start the Scrapy task (pess a button and then it triggers an API endpoint to start the Scrapy task)(edited)
Thanks for reading my confusing situation, and I'm looking forward to your advice

meager anchor
#

@wintry raven the official tutorial

ornate coral
#

what could someone do if they had the SECRET_KEY of a running Django server?

fiery kestrel
#

can someone walk me through this?

goal: how to center google search results

site: https://www.google.com/search?q=css+guide&tbs=qdr:y

using: https://chrome.google.com/webstore/detail/stylus/clngdbkpkpeebahjckkjfobafhncgmne

or : https://chrome.google.com/webstore/detail/styleurl/emplcligcppnlalfjknjbanolhlnkmgp

or: https://chrome.google.com/webstore/detail/live-editor-for-css-less/ifhikkcafabcgolfjegfcgloomalapol

whichever you think is simplier

have no idea how to use chrome inspector thing, is it simple?

is this basic or phd level css?

native tide
#

anyone know any good library for sending sms?

keen ore
#

Using: Flask
I have this in my routes.py

@app.route('/logout')
@login_required
def logout():
    logout_user()
    flash("Logged out!", 'success')
    return redirect(url_for('index'))

how should i modify it to make into a blueprint so i can have it on separate file
and what should i have in the routes
the route above is just a example

glacial turret
#

create the blueprint and use it in the same way as app

blueprint = Blueprint('auth', __name__)

@blueprint.route('/logout')
@login_required
def logout():
    ...

and then:

from login_api import blueprint as login_blueprint
...
...
app.register_blueprint(login_blueprint)
keen ore
#

and i need to have all the imports that a route requires in the blueprint file?

#

so all blueprints that use forms need to from app import forms?

glacial turret
#

you define router per blueprint, then each blueprint can have own root

#
app.register_blueprint(login_blueprint, url_prefix='/pages')
#

in this case the logout will be under /pages/logout

keen ore
#

and if i want to, have redirect(url_for("page in different blueprint")

glacial turret
#

redirect(url_for('auth.logout'))

#

where 'auth' is your blueprint name

keen ore
#

ok, thanks 😃

#

do i need to import the app to the blueprint?

#

from app import app?

glacial turret
#

no, you import blueprint to app

keen ore
#

ok

glacial turret
#

it's the whole point of having blueprints, you can share them between multiple apps

keen ore
#

ooh

glacial turret
#

you can think about them as small encapsulated apps to do one task

keen ore
#

oh ok

#

i realized that my routes.py was getting quite big

#

at +500 loc

stark crow
#

Hey guys, I would like to get into web dev as an hobby. I have been working as a ML- intern for past 4 months and I can say that I do have working knowledge in Python. Is learning Django better or do I need to learn one of the JS framework ?

deep cave
#

django is great.

#

I think you can do a lot without learning an SPA framework, but if you were trying to change careers to webdev you might be forced to learn React or Angular or something since it's in widespread use.

#

but with just some vanillajs (or jquery) and django or flask you can already do a whole lot of magic.

#

ultimately it's down to exactly how much reactivity you need on the page. if you need absolutely everything to be reactive, like a webapp in its truest sense, it's probably more trouble than its worth to try to write it in vanillajs.

#

that said, you can use django together with something like react

#

so don't consider them to be mutually exclusive

#

in fact a python webframework can be a formidable companion to an SPA framework, imo.

#

after all, we all know node.js is evil.

deep cave
#

@rough magnet if you got a question, ask it like a person

fiery kestrel
#
hearty birch
#

just tryna deploy a web app on pythonanywhere
structure looks like this
https://github.com/mushydev/a-level-cw

SyntaxError: invalid syntax
2018-09-19 17:23:54,314:   File "/var/www/mushy_pythonanywhere_com_wsgi.py", line 81, in <module>
2018-09-19 17:23:54,314:     app = create_app()
2018-09-19 17:23:54,314: 
2018-09-19 17:23:54,314:   File "/home/mushy/lore/lore/__init__.py", line 26, in create_app
2018-09-19 17:23:54,314:     from lore.auth import bp as auth_bp
2018-09-19 17:23:54,314: 
2018-09-19 17:23:54,314:   File "/home/mushy/lore/lore/auth/__init__.py", line 5, in <module>
2018-09-19 17:23:54,314:     from lore.auth import routes
2018-09-19 17:23:54,314: 
2018-09-19 17:23:54,315:   File "/home/mushy/lore/lore/auth/routes.py", line 2, in <module>
2018-09-19 17:23:54,315:     from lore.main.models import User
2018-09-19 17:23:54,315: 
2018-09-19 17:23:54,315:   File "/home/mushy/lore/lore/main/__init__.py", line 5, in <module>
2018-09-19 17:23:54,315:     from lore.main import routes

im getting this error

#

everything works locally

#

ok im now getting 499

#

client closed request

rough magnet
#

hey

#

mushy

meager anchor
#

!t ask

lavish prismBOT
#
ask

Asking good questions will yield a much higher chance of a quick response:

• Don't ask to ask your question, just go ahead and tell us your problem.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving
• Keep your patience while we're helping you.

You can find a much more detailed explanation on our website.

rough magnet
#

how do i make a quiz in python flask and link the quiz to a route

#

not familiar with python flask

#

i have made the base form of my flask project watching and learning from documentaions

#

but i am trying to add more

hearty birch
#

hi @rough magnet lol

rough magnet
#

Well u helped me today lol . Thanks @hearty birch

hearty birch
#

yw (:

brave mantle
meager anchor
#

Django-environ👍

rose shuttle
#

Heyo,
Any idea whats the best way to display a snapshot of an excel file through django?
I have a few scripts with which I process said excel file, and I just want to consolidate everything into 1 web app with 2 pages, 1 that edits what used to be edited with the scripts ( where I had to manually change values etc), and another page where people can just view a selection of the excel sheets

#

note, the excel is local, on the same machine as the web server

rough magnet
#

guys what is wrong with this code . I am trying to make a comment section

#

how do i upload code on here

neat nest
#

!t codeblock

lavish prismBOT
#
codeblock

Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.

To do this, use the following method:

```python
print("Hello world!")
```

This will result in the following:

print("Hello world!")
neat nest
#

for particularly large pieces of code you can use the uploader we have in #welcome

rough magnet
#

thank you

neat nest
#

(backticks `, not apostrophes ')

rough magnet
#

ohhh

#

thanks

#

So in routes.py - posts i have made a new route saying : @posts.route("/post/<int:post_id>/Comment", methods = ['GET', 'POST']) @login_required def new_comment(post_id): form = NewComment() if form.validate_on_submit(): comment = Comment(content = form.content.data, author = current_user) comment.content = form.content.data db.session.add(comment) db.session.commit() #Adds Post To DataBase flash("Your comment has been posted!", 'success') return redirect(url_for('main.compscipost', post_id = post.id)) return render_template('create_comment.html', title='New Comment', form = form, legend = "New Comment ") .

#

but it keeps comming up with this error

#

sqlalchemy.exc.OperationalError: <unprintable OperationalError object>

late gale
#

Guys

#

What shall i do before and after Django course

#

I have already learned the python basics

#

should i learn some html css javascript or ?

#

and yes i am a beginner

quiet solstice
#

Go make something that you would like to make and learn as you go

late gale
#

like?

quiet solstice
#

I cannot tell you what you would like to make

mighty crow
#

what do you call the my-cool-slug part of www.mycoolsite.com/myapp/my-cool-slug? google says its the url slug but theres conflicting opinions

versed lotus
#

slug is okay. Depends on the context though. A slug is usually based on another string, e.g. blog post title or something like that

mighty crow
#

in my case its made of a slugified title and an id so im not sure if it applies

#

very similar to what theonion does

versed lotus
#

yea, I'd call that a slug.

#

"My Two Hundred Little Kittens" -> slugify() -> "my-two-hundred-little-kittens"

mighty crow
#

great thanks

meager anchor
#

django calls it slug

polar wasp
#

the id and the slug are separate aiui

#

usually if there's an id you can change the slug and it'll either redirect back to the original or ignore

native tide
#

I have around 100mb of media files that my application needs to work properly. Is it ok to commit this, or is there a better way?

knotty lark
#

any of you goofballs ever use websockets in Python

rough magnet
#

the error i get is sqlalchemy.exc.InterfceError : <unprintable InterfaceError object>

digital bluff
#

@knotty lark yea, what's up

knotty lark
#

nvm just wanted to ask what modules people use most

digital bluff
#

oh

patent aspen
#
  File "D:\Desktop\templates\main.py", line 1, in <module>
    from flask import Flask, render_template
ModuleNotFoundError: No module named 'flask'``` How can I fix this?
strange thorn
#

you have to install the flask module via pip, if you dont know how to do that you should reconsider trying to write a web app in python (for now) and focus on learning the bascis of third party libraries first

patent aspen
#

I did that, I know what Im doing, I just dont know how to fix this error

#

I haveinstalled flask with pip

rough magnet
#

from Flask ?

patent aspen
#

It works on my other pc but not this one

rough magnet
#

with capital F
then a normal case

#

try that

#

sounds silly

patent aspen
#

i dont think that would be the problem because it works on my other pc

rough magnet
#

maybe u installed flask in the wrong directory

leaden parcel
#

flask should be lower

rough magnet
#

^

#

if that doesnt work

leaden parcel
#

are you using flask for a particular reason?

rough magnet
#

is ur venv enabled

patent aspen
#

backend im using it for

rough magnet
#

i need help with my flask project as well

leaden parcel
#

@rough magnet you might be better of with django

rough magnet
#

cant do that buddy

#

only got 3 days left

#

to finish this and starting it again in django will be long as i have added stuff

#

:/

leaden parcel
#

@rough magnet did you run the migration to update the database?

rough magnet
#

also python django doesnt allow for much coding

shrewd sand
#

Wrong sharp

#

Xd

rough magnet
#

thats the thing though, i didnt use migrations for my code

#

and when i try to install it

#

i get errors

leaden parcel
#

@rough magnet did you google that error?

#

you should always google the error first and read everything you find before asking anyone else

rough magnet
#

i did read it
i did what he did
still doesnt work

#

hence why i have asked here

leaden parcel
#

your example didnt do what he did?

rough magnet
#

i know

leaden parcel
#

also someone replied to your SO post

rough magnet
#

oh hold on lemme check that out @leaden parcel

#

just forgot to put the error in the post

#

@leaden parcel

alpine oak
#

I got it, nvm. nothing a couple of hours of grinding doesn't solve ❤

raven harbor
#

any one here know a dot net server?

rough magnet
#

quick question
what is the name of this {%%}

native tide
#

in jinja, they are called "block start symbol" and "block end symbol"

#

or block start string, don't remember well

rough magnet
#

thanks

brave otter
#

Hey hey, anyone know django-allauth? Trying to figure out why once I customized the login template the {% messages %} aren't working anymore (e.g. "Your username or password was incorrect", etc)

#

I used my own form rather than customizing the allauth one if that makes any difference...I would think pointing it at the same login URL should generate the same messages tho

brave otter
#

nevermind - figured it out

knotty lark
#

That's not vague at all

#

can you clarify a bit/maybe show some code :D

leaden parcel
#

you sure you want to post your mysql password?

#

i see, well it's php and this channel is for python

#

rainbow tables are terabytes in size so mysql is probably not the best option

native tide
#

anyone using django, do you use a preprocessor for your js/css

native tide
#

How do you embed python files in html?

knotty lark
#

you don't

native tide
#

And how can I make it work then?

knotty lark
#

What do you mean? What are you trying to do?

#

You can't run Python on a client's browser (barring the use of some weird wasm python implementation or some dialect of Python that can transpile to Javascript but I digress)

#

Python, in the context of web apps and websites runs on the server

native tide
#

Ok.

knotty lark
#

You can't run Python in a browser.

#

The best you can do is link a download to the script or to a standalone version built with one of the various tools (e.g pyinstaller)

#

but regardless, the user will have to download something

native tide
#

Ok.

patent aspen
#

Does anyone know why flask doesnt work for me? I have installed it with pip and done all the setup they tell you to do on their installation guide but it gives me this error Traceback (most recent call last): File "D:\Desktop\templates\main.py", line 1, in <module> from flask import Flask, render_template ModuleNotFoundError: No module named 'flask'

rigid turtle
#

How did you install it and what OS are you on?

patent aspen
#

Windows 10

#

and I installed it by doing

#

pip install flask

#

which is what their site says to do for windows 10

#

@rigid turtle

rigid turtle
#

Try opening Python and typing import flask

patent aspen
#

Alright

normal grotto
#

Hey guys, So i have created a django we application and i have this code

    class_grades = []


    for a in assignments:
        print a.subject
        class_grades.append(a.subject)

And i get this when it prints to the web

[<Class: AP Computer Science>, <Class: AP Computer Science>, <Class: AP Computer Science>]

How would i access this
<Class: AP Computer Science>
From the array?

#

like display them on the web page

brave kettle
#

I don't have a question, just wondering

wintry crest
#

Hey! It is possible to run django app on the 000webhost free plan?

#

Or any hosting service like this.

dusk spire
#

Any ideas on how to host a sanic.py server and vuejs project together?

meager anchor
#

i wouldn't recommend using sanic in production, it's pretty insecure

#

as "cool" as it may seem

#

but if you really want to use it, you gotta ask a bit more specific question

patent aspen
#

Can anyone help me out with this? I am trying to open my project, I am using vibora btw but when I do python anything.py in command prompt it says this python: can't open file 'anything.py': [Errno 2] No such file or directory

#

anything.py is the .py file i made and i saved it to my desktop

meager anchor
#

you‘re not in the same directory as the file is

patent aspen
#

So would I need to do cd D:\Desktop?

#

In cmd prompt

#

@meager anchor

meager anchor
#

try it

patent aspen
#

I would but I’m currently not home so that’s why I asked you

polar wasp
#

@patent aspen since you mentioned D:, keep in mind that in the windows command prompt, a normal cd command won't change the current drive, you need cd /d D:\desktop

patent aspen
#

Ok

#

Well now I get this error

#
  File "anything.py", line 1, in <module>
    from vibora import Vibora, JsonResponse
  File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\vibora\__init__.py", line 7, in <module>
    from .server import *
  File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\vibora\server.py", line 5, in <module>
    from signal import pause
ImportError: cannot import name 'pause'```
normal grotto
#

I know this is a repost but i never got a clear answer

Hey guys, So i have created a django we application and i have this code

    class_grades = []


    for a in assignments:
        print a.subject
        class_grades.append(a.subject)

And i get this when it prints to the web

[<Class: AP Computer Science>, <Class: AP Computer Science>, <Class: AP Computer Science>]

How would i access this
<Class: AP Computer Science>
From the array?

native tide
#

thats weird

#

whats being printed when you do a.subject?

fast saddle
#

how do i run an asyncio function in a jinja2 template for flask?

kind steppe
#

Flask doesn't use asyncio.

fast saddle
kind steppe
#

Technically yes

#

But remember, you never ask jinja to render a template, you ask flask to ask jinja to render a template

#

This assumes that you will be calling jinja from an asynchronous function, if you are not (which you are not, it is flask) then it will error

fast saddle
#

hmm...

#

me and lucy were discussing about how i can connect my discord bot to my flask site- we've come up with asyncio messaging through tcp messaging

kind steppe
#

ideally don't connect them really

fast saddle
#

i kinda have to though if i am to have a web dashboard

kind steppe
#

Make them use the same database and let the bot put things there for the site to get and vice versus

#

*vice versus

#

wow I hate my phone

fast saddle
#

but that's not all i need

#

for example i need something where pushing a button on the site will make the bot give someone a role

kind steppe
#

Then you want some kind of message broker or pubsub with both sync and async clients

fast saddle
fast saddle
#

pubsub?

#

does pubsub cost money?

rough magnet
#

@normal grotto what are you making

normal grotto
#

Im making an application for a school @rough magnet a

#

Why?

#

@native tide Its printing AP Computer Science but i need to access it from the array nto from my assignments object

#

Still no help on my question?

rough magnet
#

sorry dude . I don't use django:/

native tide
#

what version of django @normal grotto

#

[ ] is a list in python

#

oh wtf, idk

#

whatver, anyway

normal grotto
#

Yo okay new problem i fixed the last one

#

Im getting this error

Command "c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\odude\\appdata\\local\\temp\\pip-build-_lrjgf\\docutil\\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\odude\appdata\local\temp\pip-fb1ygl-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:\users\odude\appdata\local\temp\pip-build-_lrjgf\docutil\
You are using pip version 9.0.3, however version 18.0 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
#

Please help @native tide , @rough magnet

#
Collecting docutil
  Cache entry deserialization failed, entry ignored
  Cache entry deserialization failed, entry ignored
  Downloading https://files.pythonhosted.org/packages/7a/23/c6b4ef1de3b74fa8937e9f524cb7e4a49ad7a11b66379327d9b84d2f54ac/docutil-1534770134.3645716.tar.gz
Installing collected packages: docutil
  Running setup.py install for docutil ... error
    Complete output from command c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\odude\\appdata\\local\\temp\\pip-build-_lrjgf\\docutil\\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\odude\appdata\local\temp\pip-fb1ygl-record\install-record.txt --single-version-externally-managed --compile:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "c:\users\odude\appdata\local\temp\pip-build-_lrjgf\docutil\setup.py", line 27, in <module>
        "This is a bogus package that should not be installed\n\n"
    Exception: This is a bogus package that should not be installed
#

Also that

willow jolt
#
   const rows = [["Date", "Face", "Rating", ], [Date(), s + ".jpg", r ]];
   let csvContent = "data:text/csv;charset=utf-8,";
   rows.forEach(function(rowArray){
      let row = rowArray.join(",");
      csvContent += row + "\r\n";
   });

   var encodedUri = encodeURI(csvContent);
   var link = document.createElement("a");
   link.setAttribute("href", encodedUri);
   link.setAttribute("download", "ratings.csv");
   link.innerHTML= "Click Here to download";

   link.click();
#

I'm doing this experiment where I collect ratings of randomly generated faces

#

and i want to append those ratings (along with the date, face, etc.) into a preexisting csv that is edited over and over again

#

and i want to keep that csv in my remote server

#

right now, the above code downloads each input as one csv to the local pc

#

any ideas?

deep cave
#

I mean, if you have to do it with csvs and javascript, I guess you'd have to fetch the csv from the remote server, append to it, and upload it again. but this seems like a poor approach. what I would probably suggest is that you set up a simple API with Flask or something on your remote server, solve the "append to csv" problem in python, and just make simple json requests with the rating from the client.

#

but I will admit I'm a bit biased :P

willow jolt
#

So I put Python inside the html instead?

#

but like

#

im still using js

deep cave
#

basically you put a post request in your javascript. very straight forward to do. the post request contains a json object with whatever you wanna save, the rating, the face id, something like that.

#

so the javascript posts that data off to myremoteserver/api/csv_save or whatever and then on your server, you set up a simple API to listen to requests and store rating data in your csv. or database or whatever you wanna do.

#

I mean, you shouldn't let the client (the javascript) have direct access to uploading stuff to your remote server, so an API is how that kind of thing is normally handled.

#

and to be clear, a flask API is like.. a single file. it's not something that will take a long time to learn.

#

it's pretty quick to get up and running

#

is this remote server the same one that's serving your website?

willow jolt
#

yes

#

using digital ocean

deep cave
#

what'd you build the site in? just pure html?

#

or is there a webframework involved?

willow jolt
#

pure html yes

#

by web framework do you mean like drupal/wordpress

deep cave
#

no, I mean more like flask or django

#

wordpress is more of a cms

willow jolt
#

nah i didnt

#

i just plopped in a *.html

deep cave
#

well this is the kind of thing that would be much more pleasant if such a framework was involved, basically.

#

otherwise you'll probably have to resort to node.js or something evil like that

#

you're basically suffering a lack of backend

willow jolt
#

why is node js evil

deep cave
#

I was half joking when I said that, but the half that wasn't joking thinks node.js is one of many examples of trying to shoehorn javascript into roles it should not play.

#

python is a very excellent web backend, though. and flask is fun. you could convert your whole site to flask in notime and be well armed to deal with saving data to a csv file or any other kind of interaction with your server. the problem with trying to solve it in javascript is that javascript is being run on your visitors computer, but you really don't want this problem to be solved on their computer, you want it to be solved entirely on your webserver.

#

sorry that I can't give you a simple one-liner to fix it :|

willow jolt
#

it's cool

#

Thank you!

deep cave
#

no problem. and do lean on us if you decide to try to deal with that. it's not as hard as it sounds.

#

we're always happy to help :))

willow jolt
#

@deep cave If I sent the CSVs to a google drive folder instead, would I still have to use Flask?

deep cave
#

you'd probably need your google drive credentials to do that, I would think.

#

which, again, you don't want to put in your client code. then anyone could steal your google account.

willow jolt
#

i guess i could make a drive that I don't care about

deep cave
#

yeah. but at that point you're crafting very insecure and poor quality code just to get around learning something useful and idiomatic. webdev is fun, and the real adventure starts when you involve a backend.

willow jolt
#

true

rough magnet
#

Hey is there a way to Implement cross-parametrised sql in flask

#

What would it require ? If possible

knotty lark
#

what do you mean by cross parameterized sql

rough magnet
#

I am not even that sure myself

#

I think it links table but not sure cos a foreign key does the same but it's not parameterized

knotty lark
#

Well, shouldn't you know what it is if you're trying to implement it? :D

rough magnet
#

True . I tried researching it but I didn't understand .

#

Let me rephrase my question

#

What is cross-table parameterized Sql?

knotty lark
#

Not sure what you mean by that, do you just mean a parameterized sql query as in that the engine sanitizes and fills out the variables of the query for you?

rough magnet
#

wait pls explain

hearty birch
#

hi guys

#

having a little issue

tasks = self.tasks.order_by(Task.publish_date.desc()).all()

this returns a standard python list right?

#

response = {
'response': "Successfully retrieved all tasks.",
'tasks': tasks
}
return jsonify(response), 200

gives me:
TypeError: Object of type 'Task' is not JSON serializable

digital bluff
#

what is self.tasks? looks like some sql orm query

#

@hearty birch

hearty birch
#

yeah it is flask-sqlalchemy, sorry I forgot to specify

#

self - being the User object that i have

digital bluff
#

I'm guessing tasks is a list of Task models?

hearty birch
#

tasks = self.tasks.order_by(Task.publish_date.desc()).all() should return a list yeah

#

if you mean

digital bluff
#

you need to manually convert those to a json object

#

it doesnt know how

hearty birch
#

self.tasks - this is just a query object (iirc)

#

oh ok

#

so

digital bluff
#

Task is not serializable. It doesn't care about the list, but it doesnt know what to do with its contents

hearty birch
#

oh so I have to manually make a new dict{} and add to list

#

then return that, to be jsonified

digital bluff
#

you wouldnt have to change any other code

hearty birch
#

hm

#

I think i will do it manually, it might affect sql alchemy

#

okay great it works now

#

thanks

#

@digital bluff

digital bluff
#

it shouldnt affect sqlalchemy at all

brave otter
#

Hi everyone ... has anyone used django-allauth and redirected to the account_set_password view after social login? I'm trying to find the best way to do it but the docs aren't clear other than pointing me in the direction of a somewhat related overridable method ... but that won't do exactly what I need

#

basically what I would like is for users who sign up to my site via social to have to set a username/password for the local account also as a backup, upon login.

#

so basically they click "sign up with facebook" ... it grabs whatever it can from facebook and then redirects them to the set_password view and asks them to set a password for their "mysite" account. Right now it just logs them in with an unusable password.

native tide
#

i think you would need middleware to do that

rough magnet
#
    like = User.query.filter_by(username=username).first()
    if like is None:
        flash('Post is not found')
        return redirect(url_for('main.HomePage'))
    if like == current_user:
        flash('You cannot like your own posts!')
        return redirect(url_for('posts.posts', username=username))
    current_user.like(user)
    db.session.commit()
    flash('You are following {}!'.format(username))
    return redirect(url_for('users.user_post', username=username))   ```
#

i am trying to make a like button

#

but i am confused

#

would u a follow button be similar

radiant steppe
#

So, I want to put a button in my html template that fires an event that the server responds to. I'm assuming that I'm going to have to use AJAX to fire a POST request to an endpoint on the server that handles the post? I'm using Flask.

neat nest
#

sounds like a good plan

rough magnet
#

😦

sinful solstice
#

Hallo

#

I'm looking for just some tips and guidelines on Flask best practices

#

Essentially I have a bunch of data models and I want to be able to specify the SQLAlchemy to connect to them in different ways

#

Ideally I want each data model to have its own SQLAlchemy settings that can be imported by the parent app

#

I figure there must be a way to get Flask to import all the settings of the subordinate apps, or is that just not the way it's done

native tide
#

Is it possible to use jsonify on a list of objects that each contain a list also

#

Category{name:"cat1",items{jsonify list of items}}

digital bluff
#

uh yes

#

but that format isn't valid python or json

wary mantle
#

Anyone know any good tutorials for PySide2?

rough magnet
#

i keep getting the error elasticsearch.exceptions.RequestError: RequestError(400, 'number_format_exception', 'empty String')

#

when trying to make a searchbar

#

anyone no what this error means

terse zenith
#

@rough magnet it appears it does not accept null

tame viper
#

@wary mantle you'll be better off asking in #user-interfaces (looks like a misclick to me :D)

ornate coral
wary mantle
#

Oh.. wrong channel.😄

#

Thanks Juan

fast saddle
#

for flask, how do i do url_for() but with a directory?

#

rn i have py @app.route("/dash/") @app.route("/dash/<string:guild_id>") @app.route("/dash/<string:guild_id>/<string:menu>")

#

i want py redirect(url_for('dashboard'))

#

but instead of localhost:5000/dash/ i want localhost:500/dash/23940124910249102/create

queen needle
#

@fast saddle url_for('dashboard', guild_id='aaa', menu='bbb')

fast saddle
#

thank u

queen needle
#

should work like that

fast saddle
#

okay

rough magnet
#

so guys i am trying to make a comment section

#

i have made a form that kinda works

#

only problem is the comments arent displayed

#
def post(post_id):
    post = Post.query.get_or_404(post_id)
    form = NewComment()
    if form.validate_on_submit():
        comment = Comment(content=form.content.data,commenter_author= post,
            comment_author = current_user._get_current_object())
        db.session.add(comment)
        db.session.commit()
        flash('Your comment has been published.')
        return redirect(url_for('posts.post', post_id=post.id, page=-1))
    page = request.args.get('page', 1, type = int)
    if page == -1:
        page = (post.comments.count() - 1) // \
            current_app.config['FLASKY_COMMENTS_PER_PAGE'] + 1
    pagination = post.comments.order_by(Comment.date_posted.asc()).paginate(
        page, per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],
        error_out=False)
    comments = pagination.items
    return render_template('post.html', post=post, form = form ,
        comments=comments, pagination = pagination)```
#

here is the route for my posts

#
{% block content %}
<ul class="comments">
    {% for post in messages %}
        {% include "post.html" %}
    {% endfor %}

</ul>
{% endblock content %}```
#

this is my comments section ( which doesnt work i guess)

#

also called comments.html

#

here is my comment class : ```class Comment(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.Text)
content_html = db.Column(db.Text)
date_posted= db.Column(db.DateTime(), index=True, default=datetime.utcnow)
author_id = db.Column(db.ForeignKey('user.id'), nullable =False)
post_id = db.Column(db.Integer, db.ForeignKey('post.id'),nullable = False)

@staticmethod
def on_changed_content(target, value, oldvalue, initiator):
    allowed_tags = ['a', 'abbr', 'acronym', 'b', 'code', 'em', 'i',
                    'strong']
    target.content_html = bleach.linkify(bleach.clean(
        markdown(value, output_format='html'),
        tags=allowed_tags, strip=True))

def to_json(self):
    json_comment = {
        'url': url_for('api.get_comment', id=self.id),
        'post_url': url_for('api.get_post', id=self.post_id),
        'content': self.content,
        'content_html': self.content_html,
        'date_posted': self.date_posted,
        'author_url': url_for('api.get_user', id=self.author_id),
    }
    return json_comment

@staticmethod
def from_json(json_comment):
    content = json_comment.get('content')
    if content is None or content == '':
        raise ValidationError('comment does not have a content')
        return Comment(content=content)

def repr(self):
return f"Comment('{self.content}')"

db.event.listen(Comment.content, 'set', Comment.on_changed_content)```

rough magnet
#

dw solved it

#

not like anyone offers help. Since being here , i have only had two nice people answer me

fast saddle
#

damn

#

i have a problem

#

this is for flask/jinja2 <form>

#

rn after i click "Submit" it creates a dict full of the <input>s i had rn

buoyant ledge
#

What’s the standard way to handle logins? Is it like a session ID cookie with a DB query to verify IP? Or something else?

fast saddle
#

is there any possible way to make a specific set of <input>s be put into a list, and then have a dict key like "key":["input1","input2","input3"]

digital bluff
#

wut

fast saddle
#

have <input> names put into a list

queen needle
#

@fast saddle show us your Form

#

@buoyant ledge I'd say the session id stored in a cookie with the server storing the session information in a caching backend (memcached etc.) is quite common

#

Have the session id be a uuid or a crypto-secure random string from the secrets module

#

With preference for the latter

buoyant ledge
#

Right

fast saddle
#

@queen needle u still there?

raven harbor
#

please explain the difference between urlpatterns = [
path('',views.home,name='home'), and using a regular expression

wary ginkgo
#

A quick question about RestAPIs:

when I make a POST request, which is valid, but the object which i'm asking for is not found, should I return a HTTP status 404 or a 400?

i'm asking this because in IETF page they say its the current representation for the target resource which I don't know if it means a URL or the actual content of the body i'm asking. (https://tools.ietf.org/html/rfc7231#page-59)

brave mantle
#

It's a 404

#

That's your generic "I have no idea what the fuck that is"

#

400 is more of a bad request

#

like, missing parameters

wary ginkgo
#

I actually agree with that, but the arguement is that, the link is still valid, its actuallly the parameters that are wrong, in this case someone asked for a wrong id or got the name wrong... and the DB couldn't find the object.

brave mantle
#

I would still use a 404

#

personally

#

It's more descriptive of the issue

#

You'll find most APIs follow that

wary ginkgo
#

yeah I do agree with that.

#

I think ill go with that. Thanks 😉

brave mantle
#

No problem :P

native tide
wary ginkgo
#

The server has not found anything matching the *Request-URI*. No indication is given of whether the condition is temporary or permanent.
They almost always talk about the URI

#

not about the request in the body...

#

in this case the URI is valid and correct, and exists... but the body parameters don't

#

hence my doubt

native tide
#

try taking a look at 304

#

if im not mistaken thats the body responce?

wary ginkgo
#

In that case is not modified... not a Not Found... dunno if it wouldn't bring more confusion to the user.

native tide
#

You could also use 503!

#

domain name exists and is running

wary ginkgo
#

My confusion, was if we should say to the user if he did a bad request, because the parameters in the body did not matched any object in the DB... or if we would just send a Not Found... (but someone pointed that not found is for URIs... not objects)

native tide
#

why not just make a 200 with an error on the page lol

wary ginkgo
#

I dont like that trend ( i kow facebook uses it)... but sending 200 OK everytime, then you need to check the message in my opinion is not a good way of doing things

native tide
#

actually almost every popular website uses it

#

for example if you do https://github.com/rerererererererlentripent

#

itll bring up a 404 error

#

It will tell you its a 404 error but its a 200 with 404 written on it

wary ginkgo
#

chrome tells me that it returns a 404

native tide
#

o wait nvm

#

it is a 404

#

ya then just do a 404 :))

wary ginkgo
#

But in that case I actually do agree its a 404...because the URI does not exist...

native tide
#

just do a 404 with something like body did not matched any object in the DB with normal words

#

instead of complex coding words like body and object and DB

#

LOL

wary ginkgo
#

but imagine you have /get_user_by_name/ and you body is {"name":"NoneExistentObjectName"}

#

the URI is still valid and exists...but the name in the body doesn't

#

yes...i do agree with that...

#

the point here is that i dont send any info in the URI about the object...hence the URI is valid... but the body isn't, and usually when that happens is a 400 xD

#

but yeah... in this case i'll return a 404

brave mantle
#

to be fair, that could actually just be in the uri

#

in this case

wary ginkgo
#

not if it's an email

#

the @ is not allowed in the URI

#

well..it is in query parameters...

#

I might think about change it to query parameters instead of sending it in the body

keen plume
#

Reddit's API, as another example, uses 404 if you're requesting data from a subreddit that doesn't exist

brave mantle
#

you can urlencode stuff

#

that's not a problem

dense slate
#

Hey all!
I'm currently building a MUD engine (a multiplayer telnet text game) and am getting into the DB schema today. I've used Django in the past and have some aspirations to eventually have a website to output some of the game data as well as potentially using Channels/Async.

However, for the moment I'm just looking to get the DB schema going with Postgres. Is it possible to use Django for DB management and then just read/write as needed from the game?

Does django have any special ways to handle this?

wary ginkgo
#

Yes you can. You can use django just for read operations and display the data on a website... django actually makes it easy to do so. However if you create your schema outside django, it will harder to use django models, and you will have to use cursors or custom models. but that is about your only limitation.

#

or atleast that i can think of.

#

suposing you are using django just to read, it should be easy stay away from any game logic (db wise).

dense slate
#

It's just to read and potentially manipulate with the admin UI

#

The game itself would read/write as normal to the DB as if I was not using django. I just wonderred if Django had any exrta tricks to make that read/writing from the game easier.

wary ginkgo
#

manipulations, depending on their complexity, can be harder... but you can still user pure sql, so not a problem...

#

they have their own ORM... which I find quite easy to understand

#

and the ORM has a pretty good support of postgres features

dense slate
#

Agreed. My experience with it has been positive so I figured, why not just manage the DB with Django instead of manually doing it with SQL

#

Then just update the DB from the game as usual

#

Any trouble I might run into? Would SQLAlchemy provide me a better experience in this case perhaps?

wary ginkgo
#

the only issue there is the schema...

#

schemas generated outside django are harder to make it work with django models...

#

if you generate your schema in django (ie:. django models) then try to use that in your game... it should be a smooth ride most of the time...

dense slate
#

I hear a but

wary ginkgo
#

I don have much experience with SQLAlchemy... but the reviews i've read are not very good...

digital bluff
#

sqlalchemy is a good ORM

#

but its an ORM, people don't like most orms

wary ginkgo
#

If you use it for minor operation... i don't see many issues with it... some updates, some statistics and such... as long as you manage to keep the schema sane for django... it should be fine...

dense slate
#

Would it be better to just write all the SQL manually from the game?

#

Tables, etc.

#

Or maybe there's a library for doing such a thing?

wary ginkgo
#

it depends on your ease with django or with raw sql... tbh most games i've seen, and written have used some sort of ORM...

dense slate
#

This is all relatively new to me. I've made some web apps with Django and this game was my way of learning Python better.

#

So I'm trying to do some deeper research to understand what makes sense.

wary ginkgo
#

the prob with ORMs is that they generate SQL... and sometimes its not what you really want

#

its a good way to learn...

digital bluff
#

it is generally less efficient

#

unless you suck at writing sql

dense slate
#

less efficient using an ORM?

wary ginkgo
#

usually yes

digital bluff
#

it generates "best fit" queries

dense slate
#

Ok. Maybe I'll just be giving myself a bigger headache if I use Django then.

#

My thought was I could provide a website from the game data as a bonus later on quite easily.

wary ginkgo
#

You could still do it if you use raw sql...

digital bluff
#

for most databases, its a minor impact

wary ginkgo
#

with django or any other framework

dense slate
#

Oh interesting. So even if I do all the DB manipulation from the game manually for now, I can later plug that into Django?

wary ginkgo
#

ofc you can

dense slate
#

Interesting

wary ginkgo
#

but it will be harder... to use the django Models...

digital bluff
#

no??

#

just write the models to match the database schema

dense slate
#

That makes sense.

#

Thanks!

#

So if I'm creating tables, once I write the code to create a table directly from the game code for example, what happens to that code everytime I run the game to test it? Does it continue to try to create that table? Do I need something that checks the DB first? Is this usually done just manually in the shell?

wary ginkgo
#

i'm thinking about the relations and what not... but there is a ton of help on the subject... so you wont have alot of trouble

#

unless you code it... the db and its content are permanent...

dense slate
#

True. So when I write and run it the first time, that's great. What happens when I run the same code and it sees the "create table" code once again?

#

Will it ignore it?

digital bluff
#

depends on what django does

#

probably ignores it

dense slate
#

No no, I mean from the game code. I'm disregarding Django now.

#

Let's say I just write it into the game to do all the manipulations.

wary ginkgo
#

the will do whatever you tell him to do... if you tell it to create a new table... then it will try to create a new table. If the table exists you will get an exception...

#

you need to create a DB Manager to handle all the db logic

dense slate
#

Right... ok.

#

So I need code to check everything.

wary ginkgo
#

and when you are done with that... you will probably have written some sort of ORM 😃

dense slate
#

Exactly! haha

#

That's why I wondered if I should use Django.

#

Or something

wary ginkgo
#

ORM is a bit more than that

digital bluff
#

you don't need an orm, it's totally feasible to use raw queries

wary ginkgo
#

in that case what you have is just a DB State Manager

dense slate
#

ah

#

Is it worth doing that manually or instead just finding a good library to handle it?

digital bluff
#

people use an orm because it makes relationships and queries easier

wary ginkgo
#

Well... it depends you are more interested in learning to code the game...or you want to learn sql as well in the process?

#

for the 1st... use a ORM...dont mind the queries and the db by themselves... else go for raw query

polar wasp
#

eh

wary ginkgo
#

you will loose more time with raw

polar wasp
#

in languages other than python, an ORM has the advantage that you get static typing and autocomplete, which you don't typically get for "sql query in a string"

dense slate
#

More interested in programming the game, but I'll have to manipulate the data in the game code anyhow, so i guess I can't really get away from it too much?

#

I don't really care how th DB does what it does though, no.

polar wasp
#

I think pycharm can do validation and auto completion in sql queries

dense slate
#

Is PyCharm an IDE?

polar wasp
#

yeah

dense slate
#

I just write in Sublime. Not sure how PyCharm would help.

wary ginkgo
#

in sublime you need to confiure Anaconda to have those features and Clang if i'm not mistaken... i'd suggest you to use vscode and install the python plugin...

dense slate
#

I'm not sure what features you're talking about or why I would need them?

wary ginkgo
#

the autocompletion part

dense slate
#

What would I need that for?

wary ginkgo
#

quality of life...

#

and less error prone code

#

as well as intelisense

dense slate
#

I'll read up on that. I don't know if I should be worried about efficiency a the moment.

#

I just want to know how DB management works.

wary ginkgo
#

go for raw sql then

#

write your own db manager

dense slate
#

Alright, sounds like a plan.

wary ginkgo
#

it will take you more time... but you will get the underlying issues

dense slate
#

Thanks for the insight!

wary ginkgo
#

You are welcome

raven harbor
#

wts the problem

keen plume
#

Indentation is the problem

#

If you need additional details then you need to provide the relevant code

raven harbor
#

from django.db import models

class Login (models.Model):
Email = models.CharField(max_length=450)
Name = models.CharField(max_length=250)
Gender = models.CharField(max_length=30)
Person = models.CharField(max_length=100)
Password = models.CharField(max_length=250)
def_str_(self):
return self.Name

keen plume
#

!t code-block

lavish prismBOT
#
Tag not found.

code-block is an unknown tag name. Please check the spelling and try again.

keen plume
#

!t codeblock

lavish prismBOT
#
codeblock

Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.

To do this, use the following method:

```python
print("Hello world!")
```

This will result in the following:

print("Hello world!")
raven harbor
#

those are the lines and the last two causes error

keen plume
#

The body of your str function is not indented

#

You also probably shouldn't have str as a method name

raven harbor
#

what should i do now?

keen plume
#

Indent the body of your str function

raven harbor
#

thanks...

unique folio
#

Guys I have a problem with wfastcgi. I deployed a website and every so often I get this error. It seems to happen "randomly". Any advice what to look at?

2018-10-01 16:43:07.940035: Unhandled exception in wfastcgi.py: Traceback (most recent call last):
  File "D:\home\python364x64\wfastcgi.py", line 774, in main
    record = read_fastcgi_record(fcgi_stream)
  File "D:\home\python364x64\wfastcgi.py", line 158, in read_fastcgi_record
    data = stream.read(8)     # read record
OSError: [Errno 22] Invalid argument
#

It's deployed as an Azure Web App

#

It seems like there is something with the stream object, but I have no idea why. It's my first website I ever deployed so I don't know much about this subject.

summer dirge
#

hey there,

in flask and jinja2 im trying to output simple text on a webpage
my text has multiple linebreaks as \n in it.
when i use jinja to output this, it seems to ignor the linebreaks, and shows a string with multiple \n as a single line

what can i do to make linebreaks show on my site?

ps: i would prefer a way without having to replace \n with <br> on every string in my code

quiet solstice
#

You need to escape the string

summer dirge
#

care to elaborate?

quiet solstice
#

{{string.encode('string_escape')}}

#

Or replace \n with \n

summer dirge
#

do i need to call this on every string in my template? im sorry, im new to flask/jinja

quiet solstice
#

I would assume so

summer dirge
#

you would assume what? that im new or that i need to call this on every string?

quiet solstice
#

The second

summer dirge
#

i fell like youre trying to mess with me.

quiet solstice
#

Why

summer dirge
#

the second what? the second message? the second question in the second message? the second thing in the first message?

quiet solstice
#

What? That doesn't make any sense, you asked a question with two answers and it replied it was the second

summer dirge
#

hm okay

#

{{string.encode('string_escape')}}
do i need to replace string with my string or string_escape

quiet solstice
#

You call it on the string, and string_escape is what will replace \n with \\n for you

#

It escaped the second \

#

My bad

summer dirge
#

hm

#

im getting LookupError: unknown encoding: string_escape

#

oh wait? maybe theres a misunderstanding here:

"what will replace \n with\n for you"

i dont want the \n to show up as text, i want the \n to be a linebreak in my html, a <br>

quiet solstice
#

it seems like it's unicode_escape now

summer dirge
#

well

#

now it SHOWS the \n as text

#

still no linebreaks

quiet solstice
#

{% autoescape false %} {{ 'item1|item2|item3' | replace("|", "<br/>") }} {% endautoescape %}

#

Found this as a solution for that

summer dirge
#

even with that it just shows the <br> as text on the page

#

i.. am really confused

#

i just want linebreaks instead of showing \n

quiet solstice
#

The second answer looks promising

summer dirge
#

hm

#

i wil use that but if anyone has a better way of rendering \n as a newline in jinja tell me

quiet solstice
#

The best way would be to use <br/> in the base strings

summer dirge
#

i was kinda hoping there already was a way in jinja that did this

terse zenith
#

Some flask geniuses around there? It's about I18n
I'm using Flask-Babel, and everything is fine, except in my database I have tables with different column for each languages (doesn't sound optimal), example:

id titleEn titleKa
1 Hello გქრმქ

What I do sounds stupid to me: ie:
in routes.py

@app.route('/home')
def home():
    if get_locale().language == "ka":
        models.table.title = models.table.titleKa
    elif get_locale().language == "en":
        models.table.title = models.table.titleEn

Is there a way to make my database queries language dependent?
using flask-sqlalchemy

raven harbor
#

path('(?P<Login_id>[0,9]+)/',views.detail,name='detail'),

#

is that a valid code

#

ef detail(request,Login_id):
return HttpResponse("<h2>Details for Login id:"+str(Login_id)+"</h2>",{})

#

wanna print this

#

but im getting 404 error

raven harbor
#

🙄 😩 any one?

raven harbor
#

ha solved finally

keen ore
#

I need to implement a private chat feature on my flask website, where if user is offline they get all messages when they login

#

how should i approach this?

near ridge
#

You might want to look to see if there's already a plugin or something already made that you can just use

#

Creating a chat system is more complicated than it seems. And there's the old adage, "Someone's probably already done it and done it better."

inland fossil
#

So I'm trying to pass a JSON object from Flask to JS in an HTML file.

        <script>
            var user = JSON.parse(`{{ user | tojson | safe}}`);
            console.log(user)
            setTimeout(function() {
                var welcome = document.getElementById("welcome")
                welcome.innerHTML = "Welcome back, "+user.username+"!"
            }, 1000)
        </script>

I keep getting "Welcome back, undefined!" instead of "Welcome back, AmusedGrape!" (Using Discord OAuth2). I have it log what user is and I get this:

{'username': 'AmusedGrape', 'verified': True, 'locale': 'en-US', 'mfa_enabled': False, 'id': '401792058970603539', 'avatar': '73db3cc2609ecc1f25e8bad1435f8ee8', 'discriminator': '3415', 'email': 'xxxx@xxxxx.com'}

What am I doing wrong? I looked at this StackOverflow answer and it did no help. https://stackoverflow.com/questions/42499535/passing-a-json-object-from-flask-to-javascript
Any help is appreciated.

cinder juniper
#

What is your Python code?

inland fossil
#

Something along the lines of
return render_template(“dashboard.html”, guilds=guilds, user=user)
i’ll get the real code later.

cinder juniper
#

Also log user and user.username inside the timeout function as well

inland fossil
#

ok

inland fossil
#

@cinder juniper

@app.route('/me')
def me():
    discord = make_session(token=session.get('oauth2_token'))
    user = str(discord.get(API_BASE_URL + '/users/@me').json())
    guilds = str(discord.get(API_BASE_URL + '/users/@me/guilds').json())
    return render_template("dashboard.html", user=user, guilds=guilds)
#

Here is what user and user.username logged:

{'username': 'AmusedGrape', 'verified': True, 'locale': 'en-US', 'mfa_enabled': False, 'id': '401792058970603539', 'avatar': '73db3cc2609ecc1f25e8bad1435f8ee8', 'discriminator': '3415', 'email': 'xxx@xxxxx.com'}
me:9 undefined
cinder juniper
#

What does your JS look lilke now with the logs?

inland fossil
#
        <script>
            var user = JSON.parse(`{{ user | safe | tojson }}`);
            console.log(user)
            setTimeout(function() {
                console.log(user)
                console.log(user.username)
                var welcome = document.getElementById("welcome")
                welcome.innerHTML = "Welcome back, "+user.username+"!"
            }, 1000)
        </script>
cinder juniper
#

Where is this me:9 undefined coming from. That's strange

inland fossil
#

console.log(user.username)

cinder juniper
#

Yea I can see that log. But I don't understand how that's happening considering that user logs okay

inland fossil
#

yeah

#

thats my whole issue

cinder juniper
#

How about other key/values. Do they match up if you log them?

inland fossil
#

what should i log?

cinder juniper
#

All?

inland fossil
#

ok

cinder juniper
#

Or at least a couple

inland fossil
#

well there isnt much to log other than what is logged already

cinder juniper
#

I mean individual logs like console.log(user.username)

inland fossil
#

ok

cinder juniper
#

You're logs are also missing ;

inland fossil
#

i did user.id
and i got undefined as well

#

actually i dont need semicolons anymore with JS

#

soooo

#

im good there

quiet solstice
#

What does the generated javascript look like

inland fossil
#

so the issue has got to be that it isn't reading the JSON

quiet solstice
#

also using ; is considered good practise

inland fossil
#

            var user = JSON.parse(`"{\u0027username\u0027: \u0027AmusedGrape\u0027, \u0027verified\u0027: True, \u0027locale\u0027: \u0027en-US\u0027, \u0027mfa_enabled\u0027: False, \u0027id\u0027: \u0027401792058970603539\u0027, \u0027avatar\u0027: \u002773db3cc2609ecc1f25e8bad1435f8ee8\u0027, \u0027discriminator\u0027: \u00273415\u0027, \u0027email\u0027: \u0027jack@the15thshell.com\u0027}"`);
            console.log(user)
            setTimeout(function() {
                console.log(user)
                console.log(user.username)
                console.log(user.id)
                var welcome = document.getElementById("welcome")
                welcome.innerHTML = "Welcome back, "+user.username+"!"
            }, 1000)

well i think thats my issue

cinder juniper
inland fossil
#

it does parse the json GWfroggyBlobThonk

#

var user = JSON.parse({{ user | safe | tojson }});

cinder juniper
#

You have

var user = JSON.parse(`{{ user | tojson | safe}}`);

Isn't ` format string in JS?

inland fossil
#

ill try " instead

quiet solstice
#

` is for template literals

#

similar to pythons f strings

inland fossil
#

Uncaught SyntaxError: missing ) after argument list
o h

f u n

cinder juniper
#

Oh they need $ for variable right

inland fossil
#

line 5

#

var user = JSON.parse("{{ user | safe | tojson }}");

cinder juniper
#

You've swapped them haven't you?

inland fossil
#

yeha

#

yeah

#

if i use ' then it'll break the json

cinder juniper
#

user | safe | tojson vs user | tojson | safe

#

Does that matter with Flask?

inland fossil
#

idk

#

maybe

#

did nothing

brave mantle
#

don't safe the json

#

iirc it should be fine

inland fossil
#

did nothing

quiet solstice
#

the parsing json part isnt' the problem

brave mantle
#

yeah, that's true

inland fossil
#

yeah

#

then what could be the problem

cinder juniper
#

Check the source html you get, what's the JS you see there?

quiet solstice
#
var user = JSON.parse(`"{\u0027username\u0027: \u0027AmusedGrape\u0027, \u0027verified\u0027: True, \u0027locale\u0027: \u0027en-US\u0027, \u0027mfa_enabled\u0027: False, \u0027id\u0027: \u0027401792058970603539\u0027, \u0027avatar\u0027: \u002773db3cc2609ecc1f25e8bad1435f8ee8\u0027, \u0027discriminator\u0027: \u00273415\u0027, \u0027email\u0027: \u0027jack@the15thshell.com\u0027}"`);
console.log(user)
setTimeout(function() {
    console.log(user)
    console.log(user.username)
    console.log(user.id)
}, 1000)```
cinder juniper
#

I copied that JSON.parse section and I get back a string

inland fossil
#

huh

quiet solstice
#
 typeof JSON.parse(`"{\u0027username\u0027: \u0027AmusedGrape\u0027, \u0027verified\u0027: True, \u0027locale\u0027: \u0027en-US\u0027, \u0027mfa_enabled\u0027: False, \u0027id\u0027: \u0027401792058970603539\u0027, \u0027avatar\u0027: \u002773db3cc2609ecc1f25e8bad1435f8ee8\u0027, \u0027discriminator\u0027: \u00273415\u0027, \u0027email\u0027: \u0027jack@the15thshell.com\u0027}"`);
>>>string```
cinder juniper
#

Okay, so I believe I found the issue. You have single ' around your keys in the json. These must be double quotes "

#
var user = JSON.parse('{"username": "AmusedGrape", "verified": true, "locale": "en-US", "mfa_enabled": false, "id": "401792058970603539", "avatar": "73db3cc2609ecc1f25e8bad1435f8ee8", "discriminator": "3415", "email": "jack@the15thshell.com"}')```
inland fossil
#

how do i fix that? it pulls it directly from discord.

#

RegEx?

#

~~ i suck at regex ~~

cinder juniper
#

It would have to be with tojson

inland fossil
#

ok

cinder juniper
#

So try it exactly with

var user = JSON.parse('{{ user | tojson | safe}}');```
#

Or

var user = JSON.parse('{{ user | tojson }}');```
#

Matching the quotes

brave mantle
#

If your dict contains only transferrable literals, aka strings, ints, lists and other dicts

#

you don't need to parse it

quiet solstice
#

ah yes

#

JSON requires ", you can't choose for '

brave mantle
#

yeah, but python will give you ' if you stringify a dict

#

so make sure this is a dict here and not a string

cinder juniper
#

Wait a second, you have

user = str(discord.get(API_BASE_URL + '/users/@me').json())```
#

You've converted your dictionary to a string

#

Remove str

inland fossil
#

ok

#

yup

#

that did it

#

yey

polar wasp
#

@cinder juniper does .json not return a string?

#

wait, no, i'm an idiot

cinder juniper
#

Yea, took some debugging but we found the culprit

dense slate
#

Hey all, I'm currently coding a MUD (multiplayer text-game) and am wondering if it is possible to take an existing telnet game and just "plug and play" into a websocket? Or at least to have it somehow running independently from the game so I don't have to rewrite the entire game just to take advantage of (and take on the potential headaches of) async. So far it looks like I have to code async throughout the entire game code to do any type of web interface. Any thoughts on that?

quiet solstice
#

If there is an open source one you could try it

#

Most MUDs are ancient though

dense slate
#

I've written my own engine, I just don't want to have to code async throughout the entire game if I can help it.

#

Just to get a web interface going.

rare oar
#

Hi all anyone here familiar with DRF that can walk me througha couple things?

woeful sphinx
#
<td>{{item[0]}}</td>
<td>{{item[1]}}</td>
<td>{{item[2]}}</td>
<td>{{item[3]}}</td>
#example
item1 = '{:20,.2f}'.format(item[1])
print (item1)
# output : '18,446'
#

how can i do something like this within flask / jinja ?

#

i want to format the numbers like the example

meager anchor
#

@rare oar i'm sure somebody here is. you need to ask a proper question

#

!t ask

lavish prismBOT
#
ask

Asking good questions will yield a much higher chance of a quick response:

• Don't ask to ask your question, just go ahead and tell us your problem.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving
• Keep your patience while we're helping you.

You can find a much more detailed explanation on our website.

meager anchor
#

@woeful sphinx why would you cast to int in a html template?

queen needle
#

@woeful sphinx write a function or filter as normal python code and register it to jinja2

#

It will be much easier to do what you're trying to do (number formatting?) straight in python and call your filter in the template

rare oar
#

@meager anchor and others. I have a Serializer in DRF that is nested. I am using drf-nested-writable as a package to help, but when I explicitily set a ForeignKey to a serializer object, I get 'This field is required' errors in the validator, so the create/update methods never run. What is the proper way. Linking code example shortly

rough magnet
#

could someone please read this and tell me what i am doing wrong?

gaunt lava
#

quick question - is it correct to say that unicode basically aims to assign an integer number to every letter/symbol known to mankind, with the first 255 basically being ASCII

deep cave
#

sure. that's accurate enough that I wouldn't contest it.

#

they generally call them "code points", and it's usually a hexadecimal number, so "integer number" is a bit scratchy

#

but the general idea is sound

queen needle
#

A hex number is still an integer a natural number!

deep cave
#

yes. that's why I said it was accurate enough that I wouldn't contest it.

#

but it would probably be a tiny bit more precise to refer to them as codepoints with hexadecimals

#

or, something less technical like maybe "identifier"

rough magnet
#

how would i make a like button that is linked to a post and can only be liked a user

#

the user also has the option to unlike

#

using this as a guide

#

but it only makes a relationship to the user

#

i want to make a relationship to both but not sure

native tide
#

Hey everyone, I have a really stupid Django question, but I somehow don't know how to do it. I have this Form Object in the variable 'form' and I need to get the value of the 'amount' field: <InstallmentCountForm bound=True, valid=True, fields=(amount)>. form.instance.amount and form.amount both dont work..

grand badge
#

could you put your code in a code block please? @native tide

native tide
#

I solved it by myself after hours. I needed to call form.cleaned_data.amount. Thanks though.

ornate coral
#

say I have a statistics model in django that contains graph data (the x y axes would be like word count vs the actual word for most common words used in facebook comments for a given facebook page). how would you store this data in a django model? maybe a one to many relationship between each graph point and the facebook page statistics model?

noble beacon
#

So if I have 2 devices with 2 different ips on the same network, how would I get a link on one to redirect to the other web server?

queen needle
#

on what Python web framework?

dusk spire
#

Hey guys, I've been using Sanic.py and wanted to put it into a docker container. After exiting out of the docker container and trying to run the server, I keep getting a WinError5 denying python access to localhost serving. I tried running a node webapp and it worked meaning its python specific. If anyone has any advice, it would be very much appreciated. Thank You.

jagged knot
#

Anyone worked with Django Oscar before? if looking to freelance shoot me a PM

white tinsel
#

Hey, can anyone help with csrf tokens?
My overall goal of this is to create a bot that finds an item, carts it, and checksout using primarily requests. I've been through the problem with selenium but it isn't as effecient as threading and requests.
The current issue I'm having is that in order to sumbit the form data and it to accept it, we need an 'authenticity_token' which is the csrf token. I tried going through cookies and headers but it wasn't there and I was only able to find the csrf was through source.
My current code:

checkoutpage = s.get("https://www.supremenewyork.com/checkout", headers={"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36"})
csrf = re.search("name=\"csrf-token\" content=\"(.*)\" />", checkoutpage.text).group(1)
print(csrf)

produces the result:

Although this works, the only part I really need is ai7Z7TzEjnrrtD+t/roSZ1yT2g0O9OmrvilnV1VUkWKRci6D5js5f2y9o57zDKWw5KJkWzCFwYa/fSwXTT6sEQ== which I'm having trouble parsing from the source. Any ideas?

sturdy sapphire
#

so you should be able to get that out using regex, look ahead up to the " char

#
re.findall('.+?(?=")', csrf)[0]
#

@white tinsel you could test that and see if it works, and then modify your own regex accordingly

#

no, it has been checked my the mod team beforehand

white tinsel
#

@sturdy sapphire Thanks, it does indeed work!

native tide
compact lion
#

With flask, how can I use two different @app.route decorators for different methods?

spare tundra
#

@native tide is apache started?

#

@compact lion I dont undestand the question. can you explain further?

native tide
#

i opened httpd.exe

compact lion
#

File x.py:

...
@app.route("/api/v1/mods")
def get_mods():
    return jsonify(mods)

file: y.py

...
@app.route("/api/v1/mods", methods=["POST"])
def post_mods():
    # do stuff
native tide
#

just popped up command line for a split second

spare tundra
#

try runnign it from the command line so you can see any errors it throws

#

Martmists. Have you tried that?

compact lion
#

I have

#

AssertionError: View function mapping is overwriting an existing endpoint function: get_mods

spare tundra
#

what you tried @app.route("/api/v1/mods", methods=["GET"])

#

on the first one. does it still complain?>

compact lion
#

that's what it defaults to, so yes it will still complain

#

flask/app.py:1188
methods = getattr(view_func, 'methods', None) or ('GET',)

spare tundra
#

hrmmmmmm

native tide
#

um, no errors

spare tundra
#

Im going to guess flask cannot do what you want directly.

compact lion
#

fuck

#

@deep cave you ever encountered a situation like this before by any chance?

spare tundra
#
@app.route("/api/v1/mods", methods=["GET", "POST"])
def get_mods():
    if request.method == 'POST':
        post_mods()
        return posty_stuff
    else:
        return jsonify(mods)

       
#

or something to that effeect

compact lion
#

yeah we kinda can't do that with the current structure. we have one file for mod creators, one for administrators and one for all unauthenticated users

spare tundra
#

can be in the same file

#

or even the same function

compact lion
#

same function would be annoying as we have different decorators on each function to handle authentication

spare tundra
#

I see, each of your paths are for different user groups

compact lion
#

yeah

spare tundra
#

eeeeew

compact lion
#

it makes the code easier to maintain for us

spare tundra
#

im sure. i just mean eww for this situation

compact lion
#

how so

native tide
#

@spare tundra how do i narrow down an issue with no error?

spare tundra
#

unfortunalty Ive never setup Apache on windows. I would check to see if httpd.exe is still running, even after the window closes. Start there.

#

If its running and http://localhost doesnt work, its a config issue more than likley

native tide
#

i checked another tutorial

spare tundra
#

if it ISNT running, its probalbly a config issue as well, as something isn't setup incorrectly. Apache should have its own logs you can look at

native tide
#

it wanted me to do this in cmd prompt

#
Installing the 'Apache HTTP Server' service
The 'Apache HTTP Server' service is successfully installed.
Testing httpd.conf....
Errors reported here must be corrected before the service can be started.
httpd.exe: Syntax error on line 74 of C:/Apache24/Apache24/conf/httpd.conf: Cannot load modules/mod_access_compat.so into server: The specified module could not be found.```
spare tundra
#

Your directory structure is off.

#

should just be in C:\Apache24\bin....

#

not two levels.

#

may not fix this issue, but it is incorrect.

native tide
#

okay ill try, thankyou

#

oh fuck that was it mb

#

thanks : )

spare tundra
#

yay!

#

On to Flask problems 😃

native tide
#

yes, although this is only for a school project, i only need to time processes

#

actually. that's a good question for this channel i guess. what actions can i time to compare both an async and non asnyc webserver? and how would i measure them

compact lion
#

@spare tundra found a solution

routes = {}

def multiroute(path, methods=["GET"], other_methods=[]):
    if path not in routes:
        routes[path] = {"methods": methods + other_methods}
    
    def f(func):
        for method in methods:
            routes[path][method] = func

        if all(key in routes for key in routes["methods"]):
            def switch(*args, **kwargs):
                return routes[request.method](*args, **kwargs)
            app.route(path, routes["methods"])(switch)
        return func
    return f```written on phone so might have issues but this *should* work
spare tundra
#

cool. I'm not seeing how that all comes together with your decorators. (but im no Flask Guru) Good Luck!

compact lion
#

Basically if I use Multiroute instead it'll allow me to register from anywhere and it'll add it to flask once all routes are registered to it

spare tundra
#

I see you bypass the need for the route decorator, this informs the flask backend where to resolve basec on the method provided

#

then those target methods can maintina thier own auth decs etc.

compact lion
#

Yup

deep cave
#

you just make a method for each http method and inherit from methodview and you're good to go.

#

if I understood you correctly..

compact lion
#

Yeah so that still needs get and post defined in the same file

deep cave
#

what, why would you ever want anything else :(

compact lion
#

Just for consistency with the previous code this replaces I think I'll use the abuse that is my multiroute

#

We have different files for each user group

#

unauthenticated, mod devs, and site admins

deep cave
#

okay. that is an unusual way to go about it.

compact lion
#

GET is public on path x, but POST is only mod dev, same with PATCH

deep cave
#

I would just have one file for that endpoint, use methodview to get a different method for every http method, and manage user groups with a decorator.

compact lion
#

Hmm

#

Would get messy with 200 files for every endpoint though

deep cave
#

you have 200 endpoints?

compact lion
#

Well more like 75

deep cave
#

so 75 endpoints in one file isnt more messy?

#

:p

compact lion
#

75 planned* 30 implemented

#

Nah it's like 40 per file roughly

deep cave
#

well, shrug. thats my advice anyway. you guys do you, though.

compact lion
#

And since we're using the same framework we made for Code Jam 2 it looks decently good

novel estuary
#

hey guys

#

sorry if this question has been asked a million times, i did search this channel but I couldn't find a conclusive answer

#

but what's a good book for learning django? I'd like to build a simple to-do list app that I can use on a daily basis and that'll teach me the basics of learning how to build web apps

#

I came across a few but I'm confused about the versioning. There are some for 2.1 some for 1.7 and I'm wondering if this makes that big of a difference

#

Or do you think the Django tutorial in the documentation is pretty good? I'm going through it now and while I do have a few questions, it seems to make basic sense

queen needle
#

Last time I learnt Django, the official docs seemed pretty good

#

Of course your level in python/coding in general matters

#

If you're looking for other sources I'd say try to find something that matches at least the major version, 2.*

novel estuary
#

I'm wondering if there's something that matches the Ruby on Rails Tutorial by Micheal Hartl. My friend who's a dev told me he basically got his first job because of that book, because it taught him not only how to build a web app, but how to deploy it and maintain it as well.

deep cave
#

a good book would be Two Scoops of Django.

#

although you will still need to use their official docs to learn the basics

#

two scoops is more focused on best practices

#

but it's a very very good book.

#

and the docs for Django are some of the best docs for any project.

#

the gold standard for docs in python

#

the djangogirls tutorial is a fairly well recognized place to start, though

#

if you don't wanna dive into docs quite yet