#web-development
2 messages · Page 14 of 1
ok then take ur time
dude you gonna have to start googling lol
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
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.
show code mr darkness
@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
@grand badge sure im doing that but just want to know how hard it is..
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
in the case of flask, you could store it in the session. You have to set the "SECRET_KEY" option to use sessions
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
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.
Celery is a task queue, rmq a message broker, those don't have a lot to do with sessions in itself
Thanks, I'll check it out, it's been a minute since I've worked in Flask.
@meager anchor Do you know of any good production level Flask projects I could read through to see some good practices?
Hmmm, maybe our website? https://gitlab.com/python-discord/projects/site
I'm more active in the django realms of things, so that's all I can think of
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.
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
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
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?
Errr that's vague but no
Even if two tables define a relationship you have to add the data
thanks shawn this helps a lot.. any advice on how to achieve this ?
just.. add the data to both.
Will do.
@meager anchor im trying to add water repelent effect throughout my website in everypage is it possible??
computers can do anything if you work at it hard enough
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
@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
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
its completely fine , u can tell me weather uv seen something like this used in webpages
this kind of effect in my website when thhey clicked anywhere
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
ill make it soon
please tell me its possible in this page or not ill start working
look at the source code
see how he did it
and also look at the console etc
all very helpful
the bandwidth cap would be a dealbreaker for me.
but depends on the specs of the server.
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
wat.
I know a guy
any server in the world is worth 15 bucks one time charge.
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
good stuff
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
@autumn flare I'm interested. Cause that's a hot deal
@golden ferry Sure I'll check with him! And yeah, it's an insanely amazing deal...
@autumn flare * winks intensely at User *
stares loudly
@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)
yeaaaaa, but i kinda want to run jenkins and openvpn and hastebin and a bot
@digital bluff Yeah, as long as it is legal you're good
but its a webserver
how do i install/manage those services?
does it allow ssh access?
yeah it allows ssh
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.
It's installed in cPanel already
@deep cave Yeah it kinda went overboard when I tried to hit you up and everyone got interested 😅
how do I know you're not the friend and that this is how you get people to paypal you 20 bucks.
🤔
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
anyway let's just get this channel back to what it's about, which is helping people with webdev questions.
well generally you would get some more info before you pay him
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.
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?
Yes it's possible, but you could do that all client side if you don't need to process anything
yeah, it can be client side, no problem w/ that
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
Watch so it doesn't allow them to direct to any directory you didnt intend for though
@knotty lark how exactly would I do that? I am not that fammiliar w/ HTML so any help/resources would be appreciated.
The jabascript location API
<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
that doesn't work on older browsers
You sure you wanna do it client side?
Yeah ideally this seems like something that would benefit from some server side validation
Does it matter if people can just go to all the numbers?
I'm not completely sure how permissions and etc work if it's a script directing you
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
but what if ../admin was passed
@olive wharf it's like a normal get request
I mean that's not a security problem about the redirect script
it's server side permissions that are fudged
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?
As I said, my JS is rusty, you might have to fix the onclick handler function or something : )
Well my client side JS anyways
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!
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!
What beginner Django tutorials do you guys recommend? I've used php all my life and want to get into Python for backend development.
corey schafer is very reputable, he made a django tutorial playlist just a couple weeks ago that you can take a look at here: https://www.youtube.com/watch?v=UmljXZIypDc&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p
In this Python Django Tutorial, we will be learning how to get started using the Django framework. We will install the necessary packages and get a basic app...
@wintry raven
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
@wintry raven the official tutorial
what could someone do if they had the SECRET_KEY of a running Django server?
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?
Redesign the web with Stylus, a user styles manager. Stylus allows you to easily install themes and skins for many popular sites.
anyone know any good library for sending sms?
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
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)
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?
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
and if i want to, have redirect(url_for("page in different blueprint")
no, you import blueprint to app
ok
it's the whole point of having blueprints, you can share them between multiple apps
ooh
you can think about them as small encapsulated apps to do one task
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 ?
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.

@rough magnet if you got a question, ask it like a person
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?
Redesign the web with Stylus, a user styles manager. Stylus allows you to easily install themes and skins for many popular sites.
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
!t 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.
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
hi @rough magnet lol
Well u helped me today lol . Thanks @hearty birch
yw (:
Django-environ👍
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
guys what is wrong with this code . I am trying to make a comment section
how do i upload code on here
!t 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!")
thank you
(backticks `, not apostrophes ')
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>
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
Go make something that you would like to make and learn as you go
like?
I cannot tell you what you would like to make
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
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
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
yea, I'd call that a slug.
"My Two Hundred Little Kittens" -> slugify() -> "my-two-hundred-little-kittens"
great thanks
django calls it slug
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
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?
any of you goofballs ever use websockets in Python
the error i get is sqlalchemy.exc.InterfceError : <unprintable InterfaceError object>
@knotty lark yea, what's up
nvm just wanted to ask what modules people use most
oh
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?
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
I did that, I know what Im doing, I just dont know how to fix this error
I haveinstalled flask with pip
from Flask ?
It works on my other pc but not this one
i dont think that would be the problem because it works on my other pc
maybe u installed flask in the wrong directory
flask should be lower
are you using flask for a particular reason?
is ur venv enabled
backend im using it for
i need help with my flask project as well
@rough magnet you might be better of with django
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
:/
@shrewd sand run these commands and see if there is a flask in one of the listed paths: https://stackoverflow.com/questions/897792/where-is-pythons-sys-path-initialized-from
@rough magnet did you run the migration to update the database?
also python django doesnt allow for much coding
thats the thing though, i didnt use migrations for my code
and when i try to install it
i get errors
@rough magnet did you google that error?
the first result is https://stackoverflow.com/questions/29888698/sqlalchemy-exc-interfaceerror-unprintable-interfaceerror-object
you should always google the error first and read everything you find before asking anyone else
your example didnt do what he did?
i know
also someone replied to your SO post
oh hold on lemme check that out @leaden parcel
just forgot to put the error in the post
@leaden parcel
I got it, nvm. nothing a couple of hours of grinding doesn't solve ❤
any one here know a dot net server?
quick question
what is the name of this {%%}
in jinja, they are called "block start symbol" and "block end symbol"
or block start string, don't remember well
thanks
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
nevermind - figured it out
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
anyone using django, do you use a preprocessor for your js/css
How do you embed python files in html?
you don't
And how can I make it work then?
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
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
Ok.
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'
How did you install it and what OS are you on?
Windows 10
and I installed it by doing
pip install flask
which is what their site says to do for windows 10
@rigid turtle
Try opening Python and typing import flask
Alright
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
has anyone used https://github.com/wagtail/wagtail ?
I don't have a question, just wondering
Hey! It is possible to run django app on the 000webhost free plan?
Or any hosting service like this.
i wouldn't recommend using sanic in production, it's pretty insecure
as "cool" as it may seem
see https://www.reddit.com/r/Python/comments/876msl/sanic_python_web_server_thats_written_to_die_fast/
224 votes and 40 comments so far on Reddit
but if you really want to use it, you gotta ask a bit more specific question
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
you‘re not in the same directory as the file is
try it
I would but I’m currently not home so that’s why I asked you
@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
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'```
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?
how do i run an asyncio function in a jinja2 template for flask?
Flask doesn't use asyncio.
@kind steppe is http://jinja.pocoo.org/docs/2.9/api/#async-support irrelevant to what i'm doing?
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
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
ideally don't connect them really
i kinda have to though if i am to have a web dashboard
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
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
Then you want some kind of message broker or pubsub with both sync and async clients
https://asyncio.readthedocs.io/en/latest/tcp_echo.html was recommended by lucy so i started to use this
@normal grotto what are you making
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?
sorry dude . I don't use django:/
what version of django @normal grotto
[ ] is a list in python
oh wtf, idk
whatver, anyway
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
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?
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
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?
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
why is node js evil
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 :|
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 :))
@deep cave If I sent the CSVs to a google drive folder instead, would I still have to use Flask?
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.
i guess i could make a drive that I don't care about
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.
true
Hey is there a way to Implement cross-parametrised sql in flask
What would it require ? If possible
what do you mean by cross parameterized sql
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
Well, shouldn't you know what it is if you're trying to implement it? :D
True . I tried researching it but I didn't understand .
Let me rephrase my question
What is cross-table parameterized Sql?
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?
wait pls explain
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
yeah it is flask-sqlalchemy, sorry I forgot to specify
self - being the User object that i have
I'm guessing tasks is a list of Task models?
tasks = self.tasks.order_by(Task.publish_date.desc()).all() should return a list yeah
if you mean
Task is not serializable. It doesn't care about the list, but it doesnt know what to do with its contents
oh so I have to manually make a new dict{} and add to list
then return that, to be jsonified
you can also make your Task class act like a dict https://docs.python.org/3/reference/datamodel.html?emulating-container-types#emulating-container-types
you wouldnt have to change any other code
hm
I think i will do it manually, it might affect sql alchemy
okay great it works now
thanks
@digital bluff
it shouldnt affect sqlalchemy at all
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.
i think you would need middleware to do that
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
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.
sounds like a good plan
😦
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
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}}
Anyone know any good tutorials for PySide2?
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
@rough magnet it appears it does not accept null
@wary mantle you'll be better off asking in #user-interfaces (looks like a misclick to me :D)
moved my question to #tools-and-devops
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
@fast saddle url_for('dashboard', guild_id='aaa', menu='bbb')
thank u
should work like that
okay
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)```
if u want a better understanding of what i do . I used this book https://doc.lagout.org/programmation/python/Flask Web Development_ Developing Web Applications with Python [Grinberg 2014-05-18].pdf
the github for the books code : https://github.com/miguelgrinberg/flasky/tree/master/app/templates
dw solved it
not like anyone offers help. Since being here , i have only had two nice people answer me
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
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?
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"]
wut
have <input> names put into a list
@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
Right
@queen needle u still there?
here's my current whole form: https://hastebin.com/avekoxulex.xml
please explain the difference between urlpatterns = [
path('',views.home,name='home'), and using a regular expression
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)
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
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.
I would still use a 404
personally
It's more descriptive of the issue
You'll find most APIs follow that
No problem :P
Learn about the http status codes: what they are and what they mean. They are a great clue on why a transaction went wrong
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
In that case is not modified... not a Not Found... dunno if it wouldn't bring more confusion to the user.
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)
why not just make a 200 with an error on the page lol
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
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
chrome tells me that it returns a 404
But in that case I actually do agree its a 404...because the URI does not exist...
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
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
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
Reddit's API, as another example, uses 404 if you're requesting data from a subreddit that doesn't exist
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?
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).
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.
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
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?
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...
I hear a but
I don have much experience with SQLAlchemy... but the reviews i've read are not very good...
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...
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?
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...
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.
the prob with ORMs is that they generate SQL... and sometimes its not what you really want
its a good way to learn...
less efficient using an ORM?
usually yes
it generates "best fit" queries
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.
You could still do it if you use raw sql...
for most databases, its a minor impact
with django or any other framework
Oh interesting. So even if I do all the DB manipulation from the game manually for now, I can later plug that into Django?
ofc you can
Interesting
but it will be harder... to use the django Models...
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?
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...
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?
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.
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
and when you are done with that... you will probably have written some sort of ORM 😃
ORM is a bit more than that
you don't need an orm, it's totally feasible to use raw queries
in that case what you have is just a DB State Manager
ah
Is it worth doing that manually or instead just finding a good library to handle it?
people use an orm because it makes relationships and queries easier
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
eh
you will loose more time with raw
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"
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.
I think pycharm can do validation and auto completion in sql queries
Is PyCharm an IDE?
yeah
I just write in Sublime. Not sure how PyCharm would help.
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...
I'm not sure what features you're talking about or why I would need them?
the autocompletion part
What would I need that for?
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.
Alright, sounds like a plan.
it will take you more time... but you will get the underlying issues
Thanks for the insight!
You are welcome
Indentation is the problem
If you need additional details then you need to provide the relevant code
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
!t code-block
code-block is an unknown tag name. Please check the spelling and try again.
!t 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!")
those are the lines and the last two causes error
The body of your str function is not indented
You also probably shouldn't have str as a method name
what should i do now?
thanks...
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.
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
You need to escape the string
care to elaborate?
do i need to call this on every string in my template? im sorry, im new to flask/jinja
I would assume so
you would assume what? that im new or that i need to call this on every string?
The second
i fell like youre trying to mess with me.
Why
the second what? the second message? the second question in the second message? the second thing in the first message?
What? That doesn't make any sense, you asked a question with two answers and it replied it was the second
hm okay
{{string.encode('string_escape')}}
do i need to replace string with my string or string_escape
You call it on the string, and string_escape is what will replace \n with \\n for you
It escaped the second \
My bad
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>
it seems like it's unicode_escape now
{% autoescape false %} {{ 'item1|item2|item3' | replace("|", "<br/>") }} {% endautoescape %}
Found this as a solution for that
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
The second answer looks promising
hm
i wil use that but if anyone has a better way of rendering \n as a newline in jinja tell me
The best way would be to use <br/> in the base strings
i was kinda hoping there already was a way in jinja that did this
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
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
🙄 😩 any one?
ha solved finally
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?
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."
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.
What is your Python code?
Something along the lines of
return render_template(“dashboard.html”, guilds=guilds, user=user)
i’ll get the real code later.
Also log user and user.username inside the timeout function as well
ok
@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
What does your JS look lilke now with the logs?
<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>
Where is this me:9 undefined coming from. That's strange
console.log(user.username)
Yea I can see that log. But I don't understand how that's happening considering that user logs okay
How about other key/values. Do they match up if you log them?
what should i log?
All?
ok
Or at least a couple
well there isnt much to log other than what is logged already
I mean individual logs like console.log(user.username)
ok
You're logs are also missing ;
i did user.id
and i got undefined as well
actually i dont need semicolons anymore with JS
soooo
im good there
What does the generated javascript look like
so the issue has got to be that it isn't reading the JSON
also using ; is considered good practise
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
You have
var user = JSON.parse(`{{ user | tojson | safe}}`);
Isn't ` format string in JS?
ill try " instead
Uncaught SyntaxError: missing ) after argument list
o h
f u n
Oh they need $ for variable right
You've swapped them haven't you?
did nothing
the parsing json part isnt' the problem
yeah, that's true
Check the source html you get, what's the JS you see there?
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)```
I copied that JSON.parse section and I get back a string
huh
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```
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"}')```
how do i fix that? it pulls it directly from discord.
RegEx?
~~ i suck at regex ~~
It would have to be with tojson
ok
So try it exactly with
var user = JSON.parse('{{ user | tojson | safe}}');```
Or
var user = JSON.parse('{{ user | tojson }}');```
Matching the quotes
If your dict contains only transferrable literals, aka strings, ints, lists and other dicts
you don't need to parse it
yeah, but python will give you ' if you stringify a dict
so make sure this is a dict here and not a string
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
Yea, took some debugging but we found the culprit
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?
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.
Hi all anyone here familiar with DRF that can walk me througha couple things?
<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
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.
@woeful sphinx why would you cast to int in a html template?
@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
@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
could someone please read this and tell me what i am doing wrong?
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
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
A hex number is still an integer a natural number!
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"
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
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..
could you put your code in a code block please? @native tide
I solved it by myself after hours. I needed to call form.cleaned_data.amount. Thanks though.
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?
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?
on what Python web framework?
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.
Anyone worked with Django Oscar before? if looking to freelance shoot me a PM
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?
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
@sturdy sapphire Thanks, it does indeed work!
i am trying to set up an apache server, i have got to point 16 on the link below but my local host has an unable to connnect error
https://www.storehubs.com/Blog/deploy-python-flask-application-apache-windows-server/
With flask, how can I use two different @app.route decorators for different methods?
@native tide is apache started?
@compact lion I dont undestand the question. can you explain further?
i opened httpd.exe
just popped up command line for a split second
try runnign it from the command line so you can see any errors it throws
Martmists. Have you tried that?
I have
AssertionError: View function mapping is overwriting an existing endpoint function: get_mods
what you tried @app.route("/api/v1/mods", methods=["GET"])
on the first one. does it still complain?>
that's what it defaults to, so yes it will still complain
flask/app.py:1188
methods = getattr(view_func, 'methods', None) or ('GET',)
hrmmmmmm
um, no errors
Im going to guess flask cannot do what you want directly.
@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
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
same function would be annoying as we have different decorators on each function to handle authentication
I see, each of your paths are for different user groups
yeah
eeeeew
it makes the code easier to maintain for us
im sure. i just mean eww for this situation
how so
@spare tundra how do i narrow down an issue with no error?
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
i checked another tutorial
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
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.```
Your directory structure is off.
should just be in C:\Apache24\bin....
not two levels.
may not fix this issue, but it is incorrect.
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
@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
cool. I'm not seeing how that all comes together with your decorators. (but im no Flask Guru) Good Luck!
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
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.
Yup
@compact lion the way to do that is with class based views. the built in pluggable MethodView makes it trivial. http://flask.pocoo.org/docs/1.0/api/#flask.views.MethodView
you just make a method for each http method and inherit from methodview and you're good to go.
if I understood you correctly..
Yeah so that still needs get and post defined in the same file
what, why would you ever want anything else :(
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
okay. that is an unusual way to go about it.
GET is public on path x, but POST is only mod dev, same with PATCH
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.
you have 200 endpoints?
Well more like 75
well, shrug. thats my advice anyway. you guys do you, though.
And since we're using the same framework we made for Code Jam 2 it looks decently good
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
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.*
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.
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

