#web-development
2 messages ยท Page 18 of 1
Yes
List of images, I want to be able to click it and then its gonna display it in my screen with a comment
ListView and DetailView?
Thats all?
are you working with Django CBVs?
What is CBV?
Class Based Views
im guessing you're using functions?
then you would just make a normal list view and a normal detail view in a function based view
Ok
when you say "comment" do you mean comment form?
I use primary key?
well, you could use primary keys, but u could also use slugs
Is slugs better?
no, but it depends on your needs
Primary key is a number, slug is a string
like first-post
are you a beginner?
Absolutely, started like month ago
I have done some projects now
Like i know basic stuff like .as_view()
hmm
And @login_required
What
what do you use .as_view() for?
I used it in last project, when I made blog
why?
i have only used it when working with CBVs
ohhh something like a quick homepage?
I could do blog posts easily and then it generated page for it
Like post/1
I gotta go sleepy
me too
is that a question?
No
Aight boys I'm back with another question. I'm using Django and DRF and the AllowPUTAsCreateMixin to PUT some data, but for some reason some of the PUTs return 400 and I can't tell why. Below are some example request.data and the responses for them.
Creates just fine:
<QueryDict: {'hero_name': ['Diablo'], 'name': ['Debilitating Flames'], 'description': ['Enemy Heroes hit by Fire Stomp are Slowed by'], 'tier': ['16'], 'order_position': ['2'], 'games
': ['1883'], 'popularity': ['14.8'], 'winrate': ['49.0']}>
web | [06/Jan/2019 14:31:57] "PUT /api/talents/Debilitating%20Flames/ HTTP/1.1" 201 191
Fails:
<QueryDict: {'hero_name': ['Diablo'], 'name': ['Domination'], 'description': ['Casting Overpower resets the cooldown of Shadow Charge.'], 'tier': ['16'], 'order_position': ['1'], 'gam
es': ['9573'], 'popularity': ['75.2'], 'winrate': ['52.7']}>
web | Bad Request: /api/talents/Domination/
web | [06/Jan/2019 14:31:57] "PUT /api/talents/Domination/ HTTP/1.1" 400 69
I have a previous version of this bot that was inserting directly to postgres and had no problems with this data, so I can't imagine it's ACTUALLY malformed data that's causing the 400 errors.
Does it fuck up only on update?
Just tried it with .post() and it looks like all the same ones failed/succeeded
@ripe pecan
As a sanity check, I checked each input with type() and they're all their proper types
This is fucking embarrassing. My model has a 50 character limit on the description field, so the failure was from descriptions longer than that. I don't remember why I set that when building the models from my old db...
Howdy people
I'm trying to deploy some python functions to AWS Lamdba/gateway using the serverless framework.
Does anyone here have experience with that?
@last forge haha, glad it's solved :)
how am i able to set limit-request-line in gunicorn
heyy
So I'm trying to create a website...
It's an online shop, to sell websites, graphics etc. on. Is there like a platform where all the payment occurs and the product automatically gets sent to the buyer, because I don't want to go through all the hassle of creating my own checkout with something like PayPal. I know Shopify does the buy-button thing, although, you have to pay for it. Are there any free alternatives ?
I do not think you can find anyone that is free @wary mantle
you might only think about no monthly fee
if there is a "no monthly fee" and "no setup fee" you would have to pay a higher Transaction fee
you can look at, Paypal, Amazon Payments, WePay, Stripe
might be many more, but im confident that the well known ones have a "free" option
Oh, ok. I'll do my research.
Thanks!
Hey, im pretty new in this stuff and im wondering why i don't see any URL headers in my POST request? It's in the Request body but i don't see anything in the URL
I'm doing a simple text input and it sends the input to a PHP file lol
I'm also using XAMPP if that's any information that needs to be known lol
Aye i got it workin
HI everyone. I'm going to venture into creating a web app. I keep reading conflicting information on Flask vs Django. Can someone shine some light? What should I use?
Its based on your preference and need. They both can create the same site. Django is more of a "batteries included" framework while Flask is more of a "Get your own batteries" framework. Django has a lot of stuff built in to the framework while in Flask, you have to install some other modules. Django makes you do things "The Django way" while Flask gives people more freedom with what a person wants to do. For example, Django comes with a built in ORM but it only works with SQL databases. Flask on the other hand, is more flexible and can let you work with NoSQL databases as long as you install the correct modules for your needs. However, because Django has a lot of things built in, it can save you the stress of choosing what you need for your project. For example, if you need an ORM in your Flask application, you'll have a lot of different options to choose from. With Django on the other hand, there is no option and you just get along with the ORM they have given you. Another reason a person might choose Django is that it can save you time writing some code that you would have to write out yourself in something like Flask.
With that said, if you want to start learning web development, a lot of people would suggest Flask as its much easier to get started with. However its not that hard to learn Django either as a first framework but the majority would suggest Flask. @somber burrow
Okay, thank you for your advice!
๐
Hey does anyone know why when i do join(',' , $row) //an array it shows the items of the array, but when i do $row[0] it says Notice: Undefined offset: 0 ??
i am not sure what this has to do with python, html, css, or js
Cause its #web-development and php is web development
@somber burrow I'll toss in support for Django as a starter. It's been a dream for me to learn and work in. Any time I've hit a wall with "I wonder if I can do that?" the answer is "Yes, and it's in the documentation." I wish my actual web team wasn't full of PHP devs, because I'd switch us to Python just for Django.
For somereason, when I try to change image at gallery/image/1/update or create new at gallery/image/new. It doesnt allow me to do so. Text can be changed, but I wanna get at least the picture creation working. I'll send you the code later. Is it like permission thing?
So I have created CBVs, for Delete, Update, Detail, List and CreateViews. I want my client to easily add more pictures to gallery, without going to admin page.
Those are .as_view()
@last forge Thank you for your input! Think after more research Iโve decided to give Django a shot. Especially after reading about some high profile websites using it with success!
For flask I wanted to make a post and Reply. I succeeded in making the post, but for the reply I had no idea where to begin
what is reply could you explain it a bit better?
@timid arrow when you post an article for an example, there are comments, and "Replies" for these comments
Django is awesome when all it's batteries work for you.
But it starts to fall apart when you need something very unusual in the web world. Sometimes 3rd party libs save the day.
Sometimes you have to implement it on your own.
And sometimes it's just better to use Flask for that project.
So I've been looking at Responder ( https://python-responder.org/ ) and Starlette ( https://www.starlette.io/ ), the project Responder is based on, and I really tried but couldn't see the advantages of using Responder vs. Starlette.
The little ASGI library that shines.
Or is it really just the API? I feel like Responder is just boilerplate on top of Starlette to make Starlette easier to use. Am I missing something?
I guess Responder has a lot of useful abstractions on top of Starlette
Anyone know why my Flask CSS can't find the pic?
I'm quite new as well, but does Flask actually read the css files? I think you need to add that to your html file instead. I'm not sure tho ๐ .
it can process them if you set them up as templates but if the css file is set up as a static file I think it will not. Whats the exact error/behavior you are getting?
hey guys, i'm trying to use flask-sqlalchemy with MySQL the problem is when i try to name a database at the
mysql://username:password@hostname/database
it gives me the error that is a "uknown database" so it seems i need to create the database... how can i do that using flask-sqlalchemy itself?! Thank you in advance ๐
at the end i did that, tho i thought would be a way to do it
Thank you for the help ๐ and play as moira, best hero ever in OW ๐

So
class User(AbstractUser):
themes = models.ManyToManyField('Theme', blank=True, related_name="themes", default='Theme.built_ins')```
class Theme(CommonFields):
name = models.CharField(max_length=25, null=True, blank=True)
is_built_in = models.BooleanField(default=False)
# TODO implement a more detailed theme option
#creator = ...
#details = ...
path = models.CharField(max_length=1000, null=True, blank=True)
@property
def built_ins(self):
return self.__class__.objects.filter(is_built_in=True)
class Meta:
verbose_name_plural = 'Themes'
Clearly doesn't work for obvious reasons
But I'm pretty sure what I'm trying to do is clear
This is django btw
It is a callable
I changed the @property to @classmethod
I'm trying to avoid circular imports
So I imagined django would somehow allow me to do it without importing Theme inside the users.py
assuming creator is a User, could you not just put the model reference in quotes there under themes and not worry about the import where the model User lives?
I almost finished the entire models section of the project
And this would be the only import between apps
So I want to manage it without importing anything between apps
And
That didn't work either
themes = models.ManyToManyField('Theme', blank=True, related_name="themes", default=Theme.built_ins)
Bare in mind the built_ins is a classmethod
so it is a callable
Maybe use signals, but in one you'd at least have to import from the app. However, you wouldn't have the model files importing
try something like this?
does it error or anything?
I'm not sure about adding the M2M relation through defaults
only other thing is use signals
But the docs says that it is possible
I'm trying to make at least one website to put on my portfolio
So I don't want something like "you could've just used x instead of y" in a possible future interview
this may help https://stackoverflow.com/questions/4924118/django-set-default-as-subset-of-manytomany-model-field
You could also just override the user save method to set the default themes too.
Yeah I don't want to go outside of the framework if it is not necessary
I mean default=1 should've worked
Or a function that returns a queryset according to the docs
I just can't figure out why dont they
Do you have a link to the doc that says it accepts a default queryset?
I'm gonna make a decorator
just like you can't really assign a value without first saving the object, then adding the m2m object
for M2M relations
Yeah I think I'm gonna make a dec that edits the save method appropriately so that I can use something like
@whatever
class whatever(Model):
x = models.ManyToManyField('whatevers')
x_defaults = callable```
hey quick django question
when i setup my template, this works; {% extends 'header.html' %} and then i decided i wanted to change the name of that file to base.html and then changed that line to ```{% extends 'base.html' %}.. but then it doesnt work.. anyone know why?
Sorry, I don't know Django :/
A methodology for building modern, scalable, maintainable software-as-a-service apps.
@calm solar any errors?
@calm solar i'm not in Django yet (started with flask, i like minimum and "power-choice" frameworks) maybe try to link the entire path something like
{% extends 'folder/base.html %}
however looking at how Django manage this feature seems pretty much equal to Flask where there is a default folder called Templates where you can use to extend content to other pages, don't really know in Django however in flask you can change this default config
You can configure Django in the settings file to point to custom template directories. https://docs.djangoproject.com/en/2.1/howto/overriding-templates/
guys
did anyone use asp.net mvc for web development?
i know this is python group but e

I'm trying to deploy a responder app to heroku
but I get this error
Deploying app on Heroku (code=H10 desc="App crashed")
I followed the folloiwing instructions: https://responder.readthedocs.io/en/latest/deployment.html#docker-deployment
at=error code=H10 desc="App crashed" method=GET path="/"
Huzzah! It's working!
See here for details if anyone else has a similar issue: https://github.com/kennethreitz/responder/issues/199
responder's docs are quite bad
I take it web sockets should be discussed in web development, so I ask, is anyone familiar with using web sockets?
can anyone help me with the problem decribed in this post: https://www.reddit.com/r/flask/comments/af5orl/af_handling_a_default_game_move_after_a_timer/?st=jquo2n49&sh=c8728954
2 votes and 4 comments so far on Reddit
Being honest i had a look through it soz i dont know
@candid basalt & @red spear it was competing with a base.html file from another project. Django has some quirks about how it finds files.
@calm solar 
Anyone used swagger for api documentation before?
is html simple?
yes
Is there a way to use Python as a backend for a webpage without hosting it on a localhost, this is because I wan't to create a Electron alike with Python using PyQt5
Trying to setup a Django app using Gunicorn and Systemd while following the Ubuntu 18 tutorial by Digital Ocean (https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04)
When I run curl --unix-socket /run/gunicorn.sock localhost, it returns with curl: (56) Recv failure: Connection reset by peer. I've followed the instructions to a T and even reset my VPS to make sure I didn't mess up the venv.
Anyone have any suggestions? All the other steps work fine, even connecting from the outside w/o the systemd process
@gaunt salmon html is simple in of itself, but somewhat difficult to write proper correct hierarchical structures
Hey there. How can I change pages on my site without refreshing the page, whilst still changing the url of the page? Kind of like a slide but pretty much want to change everything on site except from navbar and footer.
has anyone used django_comments or django-threadedcomments ? I would like to know how you customized them exactly
@wary mantle JS
@wary mantle yes, you can. Google for spa and pushstate
Oke. Thank You
is anyone here familiar with socket.io callbacks? I am having trouble making it work with flask-socket.io
on Django, i've collected two variables post.street & post.zip. i have another .py file i want to process that data and render the results. how do i pass the data from the form to the .py file and then back to the next page?
this needs some more depth
"two variables" coming "from the form" that you want "another .py file to process" and then "render the results". okay. what are you currently doing?
so the big picture is i collect info from web form. i want to put that info into a script, process it and then display the results.
so i just put the entire thing into the views.py file?
b = form.zip ```
those are in views.py
address_processor.py needs those two values to run its script.
in address_processor.py would i just from .views import form?
which all makes sense but then how do i get that info out of address_processor.py into views
Why not create function in your py file, import it into the view file and just use it?
Okay so I am having trouble while setting the font-size for h1.animated using rem unit. For some reason it says "Invalid property value". What am I doing wrong?
using pixel unit works fine. But rem is not working.
Oh.. okay
really dumb mistake. I just realized that space should not be left between the numeric value and the word "rem"
Now it is working as expected.

starting cory schafer's flask tutotial now
Cool, have fun!
in comparison to what
oh boy what did I answer to
holy discord gods, why have you forsaken me
im trying to make a web app and all was working fine and flask stopping running and i tryed to run it and it gives me this error Traceback (most recent call last): File "/Users/harrykearney/Desktop/Projects/Poster Social Media/flask_blog.py", line 2, in <module> from forms import LoginForm, RegistrationForm File "/Users/harrykearney/Desktop/Projects/Poster Social Media/forms.py", line 3, in <module> from wtforms.vaildators import DataRequired, Length ImportError: No module named vaildators
@remote dagger im doing that rn lol
.validators shouldnโt it be?
idk
o yeah
i miss spelt it
Traceback (most recent call last):
File "/Users/harrykearney/Desktop/Projects/Poster Social Media/flask_blog.py", line 2, in <module>
from forms import LoginForm, RegistrationForm
File "/Users/harrykearney/Desktop/Projects/Poster Social Media/forms.py", line 1, in <module>
from flask_wtf import FlaskForm
ModuleNotFoundError: No module named 'flask_wtf'```
that error is fairly straightforward. not sure how a modulenotfounderror is supposed to "work fine" in the first place - did you install the module?
yes
so it isnt
Requirement already satisfied: Flask in /Library/Python/2.7/site-packages (from flask_wtf) (1.0.2)
Requirement already satisfied: WTForms in ./Library/Python/2.7/lib/python/site-packages (from flask_wtf) (2.2.1)
Requirement already satisfied: Werkzeug>=0.14 in /Library/Python/2.7/site-packages (from Flask->flask_wtf) (0.14.1)
Requirement already satisfied: click>=5.1 in /Library/Python/2.7/site-packages (from Flask->flask_wtf) (7.0)
Requirement already satisfied: Jinja2>=2.10 in /Library/Python/2.7/site-packages (from Flask->flask_wtf) (2.10)
Requirement already satisfied: itsdangerous>=0.24 in /Library/Python/2.7/site-packages (from Flask->flask_wtf) (1.1.0)
Requirement already satisfied: MarkupSafe>=0.23 in /Library/Python/2.7/site-packages (from Jinja2>=2.10->Flask->flask_wtf) (1.1.0)
Might be a little off-topic, but does anyone well-versed in Javascript want to code review a tip calculator I've coded out? Basically implementing the use of objects, their properties, and functions
@ me if you're available please!
hey, iโm a beginner looking to dive into web dev and iโm just wondering if anyone has any experience with django and vuejs. does anyone know if they work well together?
or does it not matter what i use for client side
The latter.
If you are looking into SPA or just heavily AJAXed apps - check Django REST Framework.
Otherwise it's regular Django templates either way.
sorry, im a beginner, could you explain spa and ajax?
isnt ajax javascript
but is it possible to implement vue js with django
@candid basalt
SPA = single page application.
I.e. if website page does not fully reload once you click around.
Just parst of it.
AJAX is a JavaScript technology, yes.
It allows you to send requests and update data on the page dynamically without reloading the page itself.
Yes, it's possible to use vue.js with django.
ah okay
ajax sounds interesting
so you can implement things like live feeds or something like that
silly question, is rest like vue?
@candid basalt
Vue is client side framework.
Rest is server side.
These are 2 different technologies that serve different purposes and should work together.
ahh ok
I would recommend you to start with regular approach such as django templates.
ok
And once you are comfortable with it - go for javascript, vue. ajax etc.
Not quite. It's again different things that should work together.
Django templates are server side, bootstrap is client side.
oh
what can we achieve with a django template
are they like prewritten pieces of code for something like a user registration and login page
You may want to ask google about that. It's a very broad question and discord chat won't be enough to describe.
ah okay all g thanks
another question @candid basalt, whats the relation between rest and django? is it like vue js to js
Rest Framework is a framework built on top of Django Framework.
It's an extension tha allows to build APIs promptly.
ah
would it be useful to beginners?
like what are the extra features compared to normal django and would a beginner need them
@candid basalt
ah okay
theres a big sale on udemy and im wondering if i should pick up that rest and flask course
Hey. I'm trying to display all webhooks in a specific guild using Flask in a website.
@app.route('/', methods=['GET', 'POST'])
def index():
ENDPOINT = "/guilds/525724489129000970/webhooks"
URL = "https://discordapp.com/api/v6" + ENDPOINT
res = requests.get(URL,
headers={"Authorization": "Bot <censored>"})
r = res.json()
for _ in r:
flask.render_template("index.html", webhooks=f"<option>{_['name']}</option>\n")
return flask.render_template("index.html")
This is the code I've tried and it didn't work.
You should pass 'r' through your webhooks context into the template then iterate through the data in the template to display.
If you're doing some kind of form with those options and using wtforms you can use a dynamic query to fill in the options as well under the form code instead of the view.
@pine plover
Can you give me an example?
return render_template("index.html", webhooks=r)
Then use jinja2 template engine for your for loop on r inside index.html
{% for item in r %}
<option>item['name']</option>
{% endfor %}
There ya go; I forgot the {{}} as it's been awhile
That's what I was saying
Ohhhh, sorry I understood it wrong
Updated my punctuation to make my statement clearer lol
What do you mean?
This thingy is inside the select tag
Hey guys, so I built this : https://easydryclean.be/beta/index
And I would like to add some features like user authentification, a dashboard, job listings, a recommandation system. I'm wondering as I started a CS degree, I started to learn python so this is why I'm considering django. But here is main question : would it require to recode everything to make the back-end work on my current website? (I used mainly html/css and some js scripts for scroll effect and php for the contact forms). Is django the right solution in my case ?
Ik that might seems a dumb question, I just never had to deal with back-end and db, first time I'm trying to build something like that
Hello guys
Does anyone have some knowledge on creating Websocket API's? I need some help to connect to one.
@pine plover sorry got distracted with work, I'm not sure what your goal is without an explanation or seeing the current code.
@deft needle fundamentally a web site is a document using html, pictures, styling to make it look nice. Adding in Javascript to make it interactive and dynamic like an application. These are all client side operations; you create a template to design that interactive document for the client.
The backend like Django, flask, bottle, pyramid, etc. handle the server side (backend) data. An example would be selecting a table from a database and filtering the desired rows then sending it to the template to manipulate it in a pretty fashion.
@gritty locust which framework?
I know what the select tag is I'm just not understanding what you mean by accessing it? Do you mean adding the value? From client side interaction? After posting it?
Getting the value
For example I got this in my select tag: Apple, Banana
And I selected Apple
Hello @ivory crest < I have tried with some standard libraries but without success, for exemple, I'm trying to connect to this link: wss://olymptrade.com/ws2
But I just get a handshake error, 404.
after I click on submit it displays "Apple" because I selected it
{% for _ in r %}
<option value="{{ _.name }}" >{{ _.name }}</option>
{% endfor %}
So you're asking how to access it from inside the view
After post
Ugh, never mind
@ivory crest Hmm, so like, I could keep what I currently have and add smth to manage the data that the user is gonna fill in on the client side and send them to the server side and handle these data using Django for example ?
@pine plover sorry man but the question is vague and can be interrupted in different ways
It's okay
Flask HTTP methods - Learn Flask in simple and easy steps starting from basic to advanced concepts with examples including Overview, Environment, Application, Routing, Variable Rules, URL Building, HTTP Methods, Templates, Static Files, Request Object, Sending Form Data to Te...
Right above the first picture
Is that what you're asking about?
Accessing the form data after submitting inside the index view?
That was for you Rainbow
@gritty locust are you trying to connect to a third parties websites socket?
Yes
@deft needle yes you can, take a look at the Django tutorial and you'll get a solid understanding of how it works, from there you'll need to peruse the documents more to learn advanced things. I recommend reddit.com's r/django and r/djangolearning
Oh okay, will definitely take a look at that, thx for ur tips! @ivory crest
@ivory crest Yes, this is the initial data on the chrome WS window.
Looks like it's connected and sending data just fine?
Yes but this on chrome, I'm trying to connect with it on a python script, I'm trying with: ws = create_connection('wss://olymptrade.com/ds/v3
But no success at all.
Python works too, even if it's server-side
Just wondering if anyone could help me with a boostrap navbar?
!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.
@pine plover Well yeah, you can send a post request and then return something based on that
I'm not really familiar with webkit transitions, but...
Though my website works fine, I feel like it should be fixed, what do I do to get this fixed?
I have a question regarding requests_oauthlib. Is it possible to destroy a users session?
I tried looking through the docs and didn't find much on it but there could be an unconventional way to destroy a users session I'm not aware of.
For the love of God could anyone here tell me why Apache only loads index.html?
Nothing else, it totally ignores the __init__.py file & everything in it
(โฏยฐโกยฐ๏ผโฏ๏ธต โปโโป
Apache & Flask btw, it 100% refuses to even acknowledge any other html file or any code in the __init__.py file
@native tide you can probably just save the headache entirely by not using apache. nginx would be better. if you want really easy, you can use Caddy. configuration to proxy to a flask app is a single line
Just wondering how do I keep a flask website running on my vps?
When I run main.py and close the putty session the website goes offline.
Use uwsgi and nginx, don't serve flask directly from a single process
There's uwsgi alternatives like gunicorn you could use too
Going back to my original question, I'm confused as to the use of session.pop and how to properly pass stuff into it to pop a session/destroy it
does anyone know of a simple video tutorial on SQLAlchamy for Flask?
I can't really wrap my head around it :/
is None True?
Does anyone know of a free/cheap way to publicly host my django server? Its not so much a website as it just a server & I can't port forward either so I am just trying to find a way to make my server accessible.
Linode, digital ocean?
heroku free tier would be easiest
Google Cloud free teir (512mb RAM/1 core) a month, you need a credit card to keep it active though but it doesn't charge anything
@gritty halo

how do you make a website live, meaning other computers can access it other than the local host?
Depends on what web server/web framework you use
@dull ginkgo
Apache is fucking AIDS to setup due to so many config options, fyi, its all I've really used though so far ๐
oh we're using apache server @native tide
Oh, never used that before
don't use apache ๐
if you want something super easy, give Caddy a shot.
@dull ginkgo technically, setting the servers host to '0.0.0.0' instead of 'localhost' or '127.0.0.1' is what makes it visible externally.
how do i set servers host to 0.0.0.0 @junior cloak
@dull ginkgo depends on the framework/server. are you using flask or what
what is your specific problem and environment haha
Managed to figure out and finally configure heroku thanks everyone!
โค heroku
would be nice to use why you shouldn't use apache and why caddy is "super easy"
Hello, I'm still really curious and quite confused how to just destroy a users OAuth2 session with Discord OAuth. I'm using Flask with requests_oauthlib and flask's session modules. Any help is greatly appreciated!
@app.route("/logout")
def logout():
discord = make_session(token=session.get("oauth2_token"))
logout = discord.get(REVOKE_URL)
return redirect(url_for("index"))```
This is what I've got so far and the logout variable returns 404
guys i have a question.
im currently making a program that informs me with a mail when a new post releases from the site i follow.
i created a html design so it would look like better compared to plain text only
this is what i created
please dont focus on the language/colors/pictures for now
but when i run the program and it sends me mail, this is what i get
the problem is not the texts/colors etc. dont focus on that (i get the values from the site, like title,picture, date etc)
here i tried to explain what i want to do. you can see the difference between two design. my question is, what causes that? and how can i fix it? i assume its something about css. i can share the code if required. the main program is written in python but this has nothing to do with python i guess
here is the source code: https://paste.ubuntu.com/p/ZNj8tKdVBS/
the css and html mixed together and im sorry for that. the css does not work if its written in another file and called via code (as far as i know, i tried before and it didnt work. but i would be happy if there is a way to do so). so im sorry if the code looks confusing
what is the best Web Design Tool (pidgtendo, bootstrap studio, webflow) for linux?
none of them
@steel tiger when you say 'design tool' do you also mean the html generation and such or just design
yeah, those aren't really used in general much anymore these days. on any os. they are not the best
writing html/css yourself is not a great option? i ask because even pigendo and such are essentially just themin gbootstrap for you
they arent that versatile and you can theme bootstrap without them
yeah
what are some good bootstrap themes apart from bootwatches?
I know of startbootstrap.com but never tried them
so the one cross-platform design app that i actually think is decent is pinegrow
but it isnt free. download it though and try it out
they are pretty good, they are frequently updated to stay functional with bootstrap changes
for the most part anyway
you can also just adjust the variables and generate a build for yourself on the bootstrap site: https://getbootstrap.com/docs/3.4/customize/
Bootstrap, a sleek, intuitive, and powerful mobile first front-end framework for faster and easier web development.
the main issue that i have with them is that there is no full-witdh picture thing
full-width as in fill the browser window?
doing that would be super easy
something like this
oh yeah wait
it would just be a large picture outside of the container div
so it fills the viewport but also you overlay stuff on it
yeah
yeah
one more thing sorry, how would i get the <a></a> highlighting off of this card:
@steel tiger here's a contained image bg example: https://codepen.io/notdaniel/pen/WPevaN
also what do you mean about the highlight? you want the link color or the hover color or what
you dont know how to write the css to change the link color, or you want to find out what that link color is?
also link color is one of those things easy to override with the bootstrap themer
doing tons of one-off overrides is problematic
yeah
the official tutorial
corey schafer
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...
i think it would be enough to get the basics down
volcyy also suggested the official tutorial by django docs which is good for starting too
Hi! I started learning django and I am familiar with most of basics already... Looking for good resources for learning django-material , preferably articles with step-by-step examples, videos are also fine. Can anyone reccommend something?
@grand badge How can I find it?
I am new to discord, I would prefer not to scroll up into oblivion ๐
Is it pinned?
It's not that far lol
uhm i sent it a few messages before
you said you're into articles, django docs have a good beginner friendly tutorial
Yeah, right... But I was looking for django-material specific stuff ๐
And that it is
how is that? Looks like 'vanilla' django
Oh, you're talking about some extension
Well do you know how to use Django already?
Because you should start with that.
Yeah... I am familiar with basic concepts. I did few tutorials like that already
That's the whole point
Heyoo, someone here who can help me?
!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.
{{% for member in member_names %}}
<p>{{member}}<p>
{{% endfor %}}
member_names = []
for member in members:
member_names.append(member["user"]["username"])
And this is not working
I'm getting an internal server error
Traceback?
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
no error
I mean, either there is an error or there isn't
You're checking the window you started it in, right?
What webapp framework are you using?
And how are you running it?
app.run()
Rather than the flask CLI? Okay
There should definitely be some kind of output when that happens
Also, that is indeed how you iterate over a list in jinja
If you're getting an exception and Flask isn't outputting it, you might want to enable debug mode
I'm running my bot and the website
Lemme just run in separately
OK, but running the site separately will give it no direct access to your bot's memory
What happened with the bot and site for this server is that the site exposes an API, and the bot makes use of it
jinja2.exceptions.TemplateSyntaxError: unexpected '%'
What?
What what?
OHHH
You made my day!
I should point out that discord.py is not thread-safe and neither is asyncio
watch out for tricky problems
does anyone have exp with port forwarding for a flask app on pycharm?
i want to present my flask web app at school
can any one help me in.....How to create setup.py file that will contain all dependancy of my project...??
should i use caddy next time as my web server instead of apache?
You should use nginx
nginx isnt free
ah okay :P
@jagged chasm check out ngrok
It's a tunnel proxy which will assign a temporary random web address reachable on the internets without sharing your up or port forwarding.
Free account works great and very handy for sharing the development server link with someone as a preview or collaboration.
I'm using Flask, and I'm hitting my head to a wall with my json.
How would I format this better so it would have data, count: <count> & data, channel_name : <name-of-channel>?
from flask import request
from flask_restful import Resource
from model import db, Messages, MessagesSchema, Channels, ChannelsSchema
from sqlalchemy import func
class CountMessagesByChannel(Resource):
def get(self):
value = request.args.get('user_id')
if value is not None:
count = (db.session.query(func.count(Messages.message_id), Channels.channel_name)
.join(Channels)
.filter(Channels.channel_id == Messages.channel_id, Messages.user_id == value)
.group_by(Channels.channel_name)
.all())
return {'status': 'success', 'data': count}, 200
else:
return {'status': 'failed', 'message': 'This is not how it works'}, 400
@dull ginkgo if you want to do something quick/easy, yes, use caddy!
@brave mantle you should look at it too, if you havent.
yes, nginx is better, but caddy is 80% there with 1% of the complexity
I'd rather use nginx, it's very well tested and I already understand its intricacies
this is the entire config you need to proxy to a python app: domain.tld { proxy / localhost:8000 { transparent } }
I actually make super heavy use of it in my own infrastructure
That won't work for wsgi, will it?
I suppose it would if you're using gunicorn, yeah
i use it in production with gunicorn, aiohttp and uvicorn (different places of course)
caddy is written in Go and extremely fast, performance and concurrency comparable to nginx
i dont disagree with you about nginx, but in my opinion since most of these questions seem to be people super frustrated with the complexity and who just want to put the damn app on a server somewhere, it's tough to argue with caddy
you shouldnt have to spend a week figuring out a complicated web server just to run the app you already built
and from my observations in here that final step of making your new app work with a web server seems to be a big hurdle for the uninitiated
Anyone familiar with django-treebeard materialized paths and DRF? I am unable to move nodes within a serializer. It works perfectly within my classed based view. The same logic doesn't work in the serializer at run time. The tree gets corrupted. Anyone have an idea why?
caddy can also do things like automatically set up ssl via certbot, its own rate limited, caching, etc., update dns providers with current info, handle git webhooks, etc., each of these being as simple to config as what i just posted above and requiring maybe 3-5 lines in your Caddyfile
https is a one-time setup, and caddy is very immature compared to nginx
it's only a few years old, yes. but it's widely used, tested, known to be performant, and used in production in huge places. nowhere near as much as nginx, sure, but it is hard to argue with being 80% there and requiring less than five minutes to set up a proxy to a python web app
if you arent already familiar with nginx (which describes the people in here who tend to ask) it is very daunting, ive seen folks over the course of days trying to get nginx or apache to play well with their flask app
and also the use-case for these things isn't usually "i need to launch a massive enterprise web app that can handle 500k rps by this week". it's usually "i just want to put my test web app on a single server instance so people can see it"
so although i still think caddy is a fine choice for big production apps, you definitely aren't going to need the benefits it provides over nginx in this use case
if caddy can't do that, then it's probably a better use of your time to learn nginx, though
Might as well do it right the first time
if caddy cant do what?
caddy does what i think most people need and performs very well, the only argument i do fully understand is that it's just not as old as nginx or as widely used and trusted
again, learning nginx is not a bad idea, but do you really think it makes sense to spend an hour doing the Flask tutorial but then need to spend another week figuring out server instances and then nginx config and stuff just to then have the thing be on the web?
if learning caddy took any time, like learning nginx, then i would agree. but it really does not
nginx doesn't really take that much time to learn
configuring nginx really isnt rocket science
there's billions of guides on the internet, the configuration format is very human, it is well-documented
oh, and also, i dont need to compile nginx by by myself to use it commercially
i do think nginx is a huge learning curve for most people
and i also agree it's a better choice for production use. but i do think the perfect use-case is, well, most of the people who ask about it in here, who for them usually they have already been trying to figure out nginx/apache/whatever and are frustrated
when it comes down to it, i also don't believe one needs to be an expert in 12 other things other than python to be able to deploy a python app somewhere, but that's more of a philosophical thing, hah
i like heroku and container hosts because you can do exactly that -- deploy the app you built, never touch nginx config or the plethora of other things running on a linux box that are not the app you built
Honestly we mostly just get people complaining about apache, that I've seen anyway
which.. fair enough, apache is a real pain
it still isn't something you jump into in a few minutes. and it can be difficult to debug because different default configs exist on different OS package managers and such
I've only really seen two major config setups
one where you put everything into /etc/nginx/sites-enabled
and one where you want to do that and it isn't set up for you
Sorry to hijack the channel, but why I can't do this like this?
Traceback: https://paste.pythondiscord.com/xoqujavuma.py (Error was AttributeError: type object 'Messages' has no attribute 'insert')
Code:
def post(self):
server_id = request.args.get('server_id')
channel_id = request.args.get('channel_id')
message_id = request.args.get('message_id')
message_date = request.args.get('message_date')
person_name = request.args.get('person_name')
message_text = request.args.get('message_text')
user_id = request.args.get('user_id')
if server_id is not None:
if channel_id is not None:
if message_id is not None:
if message_date is not None:
if person_name is not None:
if message_text is not None:
if user_id is not None:
ins = Messages.insert().values(server_id=server_id,
channel_id=channel_id,
message_id=message_id,
message_date=message_date,
person_name=person_name,
message_text=message_text,
user_id=user_id)
print(ins.compile().params)
@hollow flower ignoring for the moment how silly those nested argument checks are.... what is Messages? is that a SQLAlchemy ORM model? Table object? Peewee? whatever it is, it does not think it has an insert attribute
Yes, db.Model is that Messages.
I'm on mobile so I can't look it up
Core and ORM are not the same
Well, no wonder it does not work.
well, no, the bigger issue isnt the session
it's that a Table from Core has an insert attribute, whereas db.Model does not
...yes. :P
Oooh, well that would explain that.
Messages(text='whatever', somefield='something') for ORM
wrapped in session.add(), yes
@brave mantle Or neither as in not a she or a he.
Core assumes you're using Table, which does have an insert() attribute and works very differently
@hollow flower is this flask? are you using flask-sqlalchemy?
Yes
The imports:
from flask import request
from flask_restful import Resource
from model import db, Messages, MessagesSchema, Channels, ChannelsSchema
from sqlalchemy import func
consult the flask-sqlalchemy docs then: http://flask-sqlalchemy.pocoo.org/2.3/quickstart/
as it works differently
but most importantly, SQLAlchemy has multiple completely different ways to work with databases
Core and ORM are not the same and cannot be used the same
I still have no idea of what the correct way to use that is.
It's a big project with a lot of moving parts, it takes most people a while to get used to
Okey, I got past that error, how do I test the query without actually executing it?
If I want to see what it would be in SQL.
Aren't you testing in a test environment?
You could turn on the sqlalchemy debug stuff so it logs all the statements
If you mean SQLALCHEMY_ECHO it is already True.
And not entirely in a test enviroment.
I have a backup of the table/database.
Don't do it
But did you mean that one?
Run it locally on your machine and test there
What would be a great way to do token auth for the API endpoints?
what kind of auth, what kind of token, etc
is your app the auth service or will it talk to an external auth service
it's easy to add a decorator to your endpoints requiring a valid auth token. the much harder thing is the rest of the tooling that assumes -- who the auth service provider is... or if it's you then how the user signed up, what kind of auth you use, how you secure/store the credentials, whether you handle access by something like sessions vs jwt, etc etc. auth can be complicated
@hollow flower but if it's something silly for now just like a hard-coded token you will use for yourself to restrict the api access to it, then that is easy
Like, I need to be able to generate long lasting tokens, and revoke if needed by demand. It's a database API basically, for a few different things that need to be able to do things with the db.
many folks will say using sessions is preferable to json web tokens because they are safer and easier for revocation
but you can also use tokens pretty easily still by doing something like, either storing all valid token ids in Redis, or do the inverse and just store any blacklisted/revoked tokens there
and just do a check on request
If you're writing an API designed to be used programmatically by other people, API keys are probably the way to go
That is correct.
Because of CSRF I wouldn't recommend sessions for that then
JWT is defintely very easy for this. hands-down
https://blog.miguelgrinberg.com/post/restful-authentication-with-flask Is this over complicating things?
but it's so easy that over recent years JWT has become the norm before people realized the revoking problems
I'm not really sure of the advantages of JWT
What would be the best approach to API keys, if not JWT?
@brave mantle yeah what else are you thinking with the word "token" if not jwt
@hollow flower that isnt too complex, that looks like your average user signup boilerplate, except no mention of invalidation/revocation
yeah but i mean arent these still all referring to a stateless token with the same drawbacks basically
Again I don't know what those are in your mind :P
What do you exactly mean by API keys in this context?
They're usually just randomly generated strings associated with an account
that's arguably worse
a JWT at least has to be decoded and validated and has things like the expire time baked into it
you can also just generate a giant random token for each api key and save that into the database, sure
both have drawbacks
Import part is the possibility to easyish revoke the key if needed.
but @hollow flower the basics of this are the same regardless. you can get started by making a decorator that you apply to your endpoints that makes sure a token was provided in the header or query string
I have not used JWTs, hence questions
tokens stored in the DB: benefit = pretty simple, easy to revoke by deleting it. downside = the strings dont also contain useful data like what parts of the api they are allowed to browse, an enforced expire time, etc, and laso that you need to hit your sql database on every request
jwt = the user's info, permissions, roles, expire time, etc. are encrypted and baked into the token string itself, so that info is there and can be validated, wont validate if it's past the expire date, and you dont need to store it in your database and slam it on each api request. downside = revocation is slightly harder, there are some security concerns
Security conserns like?
not as big of a deal now, but there used to be issues not unlike CSRF when using sessions
the bigger issue is with how lots of people use them
since they are stateless and dont need to be stored in the database, or kept in a cookie, that also means there is no obvious way to revoke them if you didnt set up a blacklist somewhere like i mentioned
So you mean, blacklist like store the key in that list, and check against it on every request?
or people would use weak keys when encrypting the JWT, which made it easier for people to hack them in order to decode, which was bad since the token also contains user data and permissions
@hollow flower yup. redis is perfect for this. and much much much faster/lighter than putting it in your database
redis will likely have responded to the token check before your sql db connection has been initiated ha
Okey, let's say that the server whould for whatever reason lose power, would that cache also be lost?
redis does have persistence, but by default it isn't instant or atomic like databases
but you can adjust it to write constantly, and also depending on your use-case the few minutes it might wait between writes may be acceptable risk
Due to redis being completely unknown to me, I have no clue about it.
start learning ๐
it's very easy
compared to most things
and beyond that, it works remarkably well at what it does. which is basically anything requiring caching or fast data retrieval
(and if you have a project that scales up and has lots of users and such, it's likely that your caching systems are using 10x more than the underlying databases and whatnot)
redis can help you do things like cache recent content, easily store lots of analytics or event data without destroying your sql database, use it to rate-limit API requests, tons more
but yeah for tokens it would be easier than using a database. just have a redis list called revokedtokens with all the ids. or one with currenttokens or something. redis does not require models or a schema or anything
wouldn't you rather use a set?
Or just use IP address restriction.
@meager anchor haha, yes when I said "list" i was not specifically referring to the redis data structure, i just meant as a psuedocode concept of a thing that holds tokens
@hollow flower an ip restriction for what?
Question to developers that frequently use both Python and Golang: What factors into your decision on whether to write an application in one language over the other?
@junior cloak The API access restriction.
@hollow flower I thought you wanted to use tokens for that, since that was your initial inquiry, asking the best way to implement tokens haha
IP restriction also doesnโt let you say โthis user can access the api, but doesnโt have write access to [whatever]โ
That is not needed atm.
Or rate limiting. But those were just some examples
Of things redis can do, not that you need them all, just as an idea of how powerful of a tool it is
Itโs more vital these days to high performance apps than many realize is all
Redis seems like overcomplicating things at this point.
I do have an idea, I could build a user portal where user could revoke the token. Does that sound like something I should look at more or is it just meh? Your thoughts?
@junior cloak
@hollow flower well, so in redis you can make a set of valid tokens by simply adding the first one while creating the new list, with sadd activetokens 123.456.678.910
you check later to see if it exists with sismember activetokens 123.456.678.910 or remove it with srem activetokens 123.456.678.910
if you think it's easier or faster to store those in a database
with a schema to manage
and build an interface to it, then be my guest
you would be a wizard ๐
i know, but i think if you spend half an hour looking into it youll see how truly easy it is
Huh. Hey dkh, we should tell everyone to use nginx!
and as opposed to something like a sql database, you can store millions of items at once with no problem and query them in fractions of a second
the speed part is vital
@brave mantle i dont actually
A relational SQL database is definitely plenty fast for this for 99% of people
in both/most situations i am pushing a very minimalist system
And they're already using one, so it's one less thing to deploy as well
haha
okay well look
i get that totally and i will back down on it
but at the same time you asked the group how we would suggest doing it
True
and that is how i have done it, and anyone who has had to do it on a web service that has hundreds or thousands of concurrent users these days is probably using redis for things like this
you are correct in that you proabbly do not need it now
Truth to be told, I looked at the Redis docs, but didn't understand most of it
There is a huge drawback to redis too
it may be vital eventually
@brave mantle Being RAM?
Yeah, my instance lacks RAM for that kind of thing.
i will back down on it but dont get upset because you asked for how we'd do it and you just dont like how i'd do it haha
I'm not upset, more like annoyed.
@brave mantle everything is loaded into memory at once in redis at all times. it does not only live in memory. it by default persist to disk every few minutes or so depending on things
and you can change that
yes, I know that
to be much more frequent, or redundant
and that's also why you store things in it like cache
I actually wish I wasn't stuck with redis for what I'm using it for but
I host a nodebb forum for an org and it was decided on early that it'd use redis instead of mongodb
but not use it as like the persistent data for all your users
now I have everything containerised, I'd rather use mongodb, but I can't move it now :P
and i would buy you a solid gold jet ski right now if you could make mongodb cache transient data on a very high-volume web app at even 15% of the performance youd get from redis
but i recognize this is not a concern for most projects at this moment
and i apologize for annoying anyone
that's not what redis is being used for
:P
which is the problem
the entire forum's storage is on redis
what are you using it for
holy shit
wait a sec... i remember years back some comment or forum startup writing about that
luckily I do have the RAM to spare
moot or something
i mean, being in RAM is very good, you just want it to also be somewhere else too
yeah, and it does flush fine, but it's not ideal
redis' insecure-by-default configuration caused a few problems as well when the hypervisor's firewall decided to not work properly
no more proxmox for me
i believe that changed in some releases in package managers at some point
so yeah that was fun
do not use proxmox
:v
oh so it was proxmox not just the redis port being open
i have never used proxmox but have largely avoided it intentionally
people were pushing it at me for a couple years
not for dev virtualization but when i was building the crazy storage shit we were using
(like 600tb+ of data on-premises that also had to be accessble over 10GbE to anyone who might need it at the time)
zfs and whatnot
I maintain a metric fuckton of containers
there's something like 100 containers on this thing
no idea really how proxmox would help but i guess people also use it for zfs and/or ceph storage and such
but it's all hobbyist stuff really
hosting for other orgs
that sort of thing
yes, proxmox has zfs
well then that explains why it came up a lot
but those servers had to do very little other than be very very fast storage
I mean, just like everything else that uses zfs, the support is experimental
but it does have it
and as youe witnessed already i tend to favor what at least i belive to be a minimalist approach unless otherwise needed
so i never bothered with it or anything else, if i ran tons of containers i might
though in my brief period of that iw as using smartos
don't bother with it for containers either
if that even exists
i dont bother with almost anything for containers
oh yeah i mean
i have 7 or 8 running right now
but im not doing hundrds at once
and i only use them to dev locally
very occasoinally something used elsewhere on the same network but internally and low volume
nothing that requires more than a shitty computer and a regular server install of your favorite distro and docker
actually this is way less than I thought, I forgot I offloaded a bunch of stuff
is that ajenti or someting
it's datadog
also, yes good lord that is a lot of containers
arch linux is in the realm of like vim
in terms of, yes it proably works the best for you
but the 1% of whom that applies to are the only ones who are able to make it work at all
90% who try to install it at the recommendation of Smart Linux Power User From IRC probably meanwhile dont even think about lnux for 6 months because of the trauma of the experience
haha, I've heard that
it's absolutely true of IRC
I've walked a bunch of people through it on this guild though and they're mostly happy with it
a few people I've recommended to use antergos or manjaro instead though
(they're arch-based but more user friendly)
i use what i use but i try to make sure to recommend things that seem like they might make sense for the audience
perhaps not always successfully, but i at least know better htan to recommend the hardest thing to someone asking for a recommendation i.e. they know nothing about it, or they would not ask
the thing with arch
is that it actually is a lot more user friendly, ONCE SET UP, than distros like ubuntu
it's getting to that point that's the problem
my flying car will be amazing once it flies instead of drives
this is mostly hyperbole
i have no issue with arch and havent tried it in years
but some of the esoteric arguments bother me when someone asking is clearly the type of person who is going to need something that works out of the box
i'll look at those
heard of manjaro, not used, not sure ive heard of the other
i think we talked the other day when i mentioned i'm on fedora 29 now, and that it's been a very long ride but 29 finally works perfectly out of the box while retaining all the things i prefer about it to ubuntu
i wasnt alone in that assessment of 29 apparently
but yeah the more, the merrier
they should all work like that eventually
this is starting to get a bit off-topic but I think arch's big strengths come in because of its package management
you're not dealing with yum, which is often ancient and breaks on python updates
you're not dealing with apt, which has a big tendency to get stuck in dependency hell and has an RCE
there is only ever one version available of any package (unless you have an older one cached) and all the versions always line up
dnf fixed most of the yum issues, and the bigger (and definitely not ready yet but impending) thing is the ostree stuff that is a gamechanger
yeah, they really would have had to fix yum
just making all packages including system updates immutable and controlled
it was pretty garbage for a while
nix style
that will change it all and i wat for that day
downloading both these isos to test later when i inevitably have something better to do but i push rationality aside to play with a distro
@prime ridge i'm about to sleep but meant to respond to this. as luck would have it, i spent about 6 months working alongside a Go wizard while we built microservices for a very high-traffic web service, constantly comparing against each other for various use cases and also trying to one-up each other. my tdlr would be... yeah, of course Go is going to perform better in most areas, as a compiled statically typed language, but there are some areas where python can come close or outperform it, which in my experience is things like performance and concurrency for high-volume web apps when it's mostly network io, little cpu work, and also if you are doing all of these things with asyncio. so, writing a websocket server or something that has 45k connected users at once is the sort of thing you can make python match or exceed at.
Python will not be comparable in performance for heavy computation, cpu-bound work, etc. You will never write a video encoder in native python that would be faster than in Go, or a JSON parser, or a 3D video game. But some of the web stuff, python can hold its weight for sure. whether python is preferable for you depends on how well you know either language and whether or not your use case actually needs the benefits you'd get from one or the other. I'd say that python made way more sense to me, the friend/coworker who was writing Go would say Go clearly made more sense, I'd say my code was easily readible and could be written faster, he'd tell me that his was type-safe and would run safer... in the end we were both happy and all of our services were extremely fast. the choice is yours ๐
When you only have a hammer, everything looks like a nail ๐
Hey
So is this tutorial by mozzila on Django good enough for an intermediate programmer like me?
@native tide What do you mean by good enough?
Thanks for the response @junior cloak! Maybe I'll wait to push for adding Go to my company's stack until they give me something CPU heavy... ๐ค
@native tide the official tutorial is also pretty good
@coral ridge I mean is it useful or should I follow something else?
@meager anchor ok care to share the link?
@native tide It seems to have the basic stuff in it that you need to know. If you're more of a visual learner, Corey Schafer has a series on his youtube channel
@prime ridge haha so you prefer Go but were just asking here? Whatโs your company build? To be clear, for most web stuff apps in python the way most people build them, Go will run circles around it. Like youโre never going to make a flask api come close to go http with goroutines
But if you are in the camp that went all-in on asyncio as opposed to who hate it, and familiar with asgi or building on top of uvloop and whatnot, then you can
And itโs all preference. I prefer python personally and know it better so it was in my own interest to try to push it as far as it could when the Go battle was happening, and I pretty much only write async code these days
If I knew Go better and the existing stack was synchronous wsgi then Iโd be pushing for Go
(Assuming of course we needed the speed benefits and the whole team could make it happen. The biggest no- no is rewriting something for no particular reason)
Hi friends, I'm looking for some suggestions on my release process. My Django app ships with some fundamental db data that I load in a migration. Every 1-2 months, an additional entry in that data needs to be added, so I would add that in a release. I'm guessing I would ship that new entry as its own migration, right? It just seems sad to have a whole migration to add one entry.
Perhaps it would be better to update/insert them every time the app starts, avoiding the migration clunkiness. At most, it's going to grow to maybe 120 entries so that's not too bad to repeat every time the app starts, right?
Iโm pretty sure I looked at them originally but ruled it out for some reason. Iโll look at it again
I think creating data migration is better, because whenever you change your model, you have to change your fixture also. After some time, it would be overwhelming.
But it is still an option though
I donโt anticipate the model changing (famous last words)
Data migrations are the way to go ๐๐ป
any1 have some free sources for someone who is a beginnger in python and wanting to learn Django?
Current stack is synchronous wsgi. We use Django and Python (sometimes flask). If we need async programming we have to setup celery workers to consume tasks, etc
@junior cloak
The entire process feels overly complex and makes deployment of small apps that need basic asynchronous actions like sending an email or pulling data from an API in the background a big chore.
hey all... making browser sources for twitch with my django site with some JS. quick question, is there a way to monitor for hits to a certain database? and display that content on a page as soon as an entry is created?
Hi people. Hope you're all well? Do you mind if I ask a question with regards to Flask-WTF?
psst, just ask ๐
OK sorry. Lol.
Apologies for my ignorance on the subject. I am just getting my feet wet with Web Dev with Python and Flask. I am trying to create an app that will take a string from an input field and convert it into a hash and display it on an output page. However, I am not sure if my form is set up correctly. When I run the application it only returns a false value and displays that the user has not inputted anything even when I type in a random string. What I would like is to have the app return back an error if nothing is entered but run the application correctly if something is entered.
from flask import Flask, render_template, request, url_for, flash, redirect
from message import MessageForm, validators, ValidationError
from cryptography.fernet import Fernet
app = Flask(name)
app.secret_key = 'development'
key = Fernet.generate_key()
f = Fernet(key)
@app.route('/', methods=['GET', 'POST'])
def home():
form = MessageForm(request.form)
if request.method == 'POST' and form.validate_on_submit():
user_message = form.message_field.data
e = user_message.encode(encoding='UTF-8')
token = f.encrypt(e)
output = bytes.decode(token)
return redirect('output.html', output=output)
return render_template('index.html', form=form)
if name == ('main'):
app.run(debug=True)
That's the code.
{% extends 'layout.html' %}
{% block body %}
{{ form.csrf_token }}
<br />
<form action="/" method="POST">
<div class="form-group">
<label style="font-weight: bold;">{{ form.message_field.label }}</label>
<input type="text" class="form-control" name="message" id="message">
<br />
<button type="submit" class="btn btn-primary btn-lg btn-block">Encrypt Message</button>
</div>
</form>
{% for message in form.message_field.errors %}
<div class="alert alert-danger" role="alert">
{{ message }}
</div>
{% endfor %}
{% endblock %}
Here is the HTML template.
Any help would be greatly appreciated. Thank you.
@prime ridge how do you do background tasks now? I canโt imagine you just block and make the client wait while you do those. You definitely donโt need to use something celery (gross) to run synchronous code without blocking. run_in_executor is the quick and dirty way to do a lot of it. Itโs small apps doing network io that benefit the most from async.
But like I mentioned, if you donโt actually need it, then youโre right, donโt bother. But some apps do, the example I mentioned when building stuff alongside Go, for instanceโthat was a web app getting hundreds to thousands of requests a second, and scaling in a way we could manage without going broke was paramount. In that situation, moving the api away from flask to aiohttp+uvloop resulted in, depending on the task, between 5x and 11x performance boost in terms of how many concurrent requests could be handled with the exact same resources, which is... insane, and for some projects necessary to survive. Most donโt โ but keep it mind for if you do grow to that point ๐ python gets a bad reputation as being slow with stuff like this but it does not have to be the case
I was saying celery for those. E.g. for api calls or emails. It's definitely not built for scaling -- you run just how many celery workers you need usually
!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!")
@primal sinew
Not sure if this is the correct channel, or if what i am asking is even supported, but i need help using an api that has a callback url and an App key (webapp) I am not sure how to call to get the data i need. I am attempting to use truecaller.com/developer.truecaller.com the websites documentation is not helpful in the slightest. i have googled, but only found oudated api information regarding the site
@grand badge Apologies, won't happen again. ๐
I don't want this
It's always coming if I reload my website.
Is there any way I can stop it?
Never mind, solved it.
Anyone able to assist with running a code block when a submit button is clicked using Flask-WTF? I have a submit button that when clicked I would like it to copy a string to the clipboard.
@brave mantle OK thanks. Will do some digging.
Is there no way to do this with another route?
Nope, the Python doesn't run in the browser
And most browsers don't want to give direct access to the clipboard either
Might output to a file in that case. I'll look into it thanks.
Having trouble outputting a text string in my template file.
Here is my app file.
from flask import Flask, render_template, request, url_for, flash, redirect
from message import MessageForm, validators, ValidationError
from flask_bootstrap import Bootstrap
from cryptography.fernet import Fernet
import pyperclip
app = Flask(__name__)
app.secret_key = 'development'
bootstrap = Bootstrap(app)
key = Fernet.generate_key()
f = Fernet(key)
@app.route('/output.<output>')
def output_render(output=None):
form = MessageForm(request.form)
form.validate_on_submit()
secret_key = bytes.decode(key)
return render_template('output.html', output=output, secret_key=secret_key)
@app.route('/', methods=['GET', 'POST'])
def home():
form = MessageForm(request.form)
form.validate_on_submit()
if request.method == 'POST' and form.validate_on_submit():
user_message = form.message_field.data
e = user_message.encode(encoding='UTF-8')
token = f.encrypt(e)
output = bytes.decode(token)
secret_key = bytes.decode(key)
copy_message = pyperclip.copy(output)
return redirect(url_for('output_render', output=output, secret_key=secret_key, user_message=user_message))
return render_template('index.html', form=form)
if __name__ == ('__main__'):
app.run(debug=True)
Here is my template.
{% extends 'layout.html' %}
{% from 'bootstrap/form.html' import render_field %}
{% block body %}
<br />
<div class="alert alert-success" role="alert">
<h2 style="text-transform: uppercase; font-weight: bold; text-align: center;">Your Original Message:</h2>
<p style="text-align: center;">{{ user_message }}</p>
</div>
<br />
<div class="alert alert-secondary" role="alert">
<h2 style="text-transform: uppercase; font-weight: bold; text-align: center;">Your Encrypted Message:</h2>
<p style="text-align: center;">{{ output }}</p>
</div>
<br />
<div class="alert alert-danger" role="alert">
<h2 style="text-transform: uppercase; font-weight: bold; text-align: center;">Your Secret Key:</h2>
<p style="text-align: center;">{{ secret_key }}</p>
</div>
<br />
<form action="POST/GET" method="/output">
<button type="button" action="{{ url_for('home') }}" class="btn btn-primary btn-lg btn-block">Copy message to clipboard</button>
</form>
<br />
{% with messages = get_flashed_messages() %}
{% if messages %}
<div class="alert alert-success" role="alert">
{{ messages }}
</div>
{% endif %}
{% endwith %}
{% endblock %}
I am trying to output the user_message to the template file but even when I pass it through it doesn't appear on my template.
How does one stop my flask app from running, currently using gunicorn and nignx?
Stop gunicorn I guess
yes, stop gunicorn. how did you start it?
Hey guys! maybe this is a stupid question
but how can I implement python in the web?
youd usually write the server side in python and use javascript or wasm etc. inside the browser
so how can I connect javascript and python?
Has anyone here used django pagedown? https://github.com/timmyomahony/django-pagedown
@twilit pier the actual pages on your website would display javascript, wherever you display the HTML
@twilit pier youd let the communicate over websockets, APIs, Forms etc
@primal sinew https://www.w3schools.com/howto/howto_js_copy_clipboard.asp this does not work?
it does ```html
<input type="text" value="Hello World" id="myInput" hidden>
<script>
function myFunction() {
var copyText = document.getElementById("myInput");
copyText.select();
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
}
</script>
<script>myFunction()</script>```
@primal sinew
Wow thanks @native tide and @coral ridge. I'll test this later as away from desk.
๐
to learn web dev, should i use colt's udemy course?
I made a website mobile first and now I want to make a media query for tablet and laptop. how do i do that?
Should this be safe for the users to be able to use it, or is it some kind of security hole
Assuming nobody else can access the user's input, it should be okay
Thanks Dude
Should I use Django + React JS. or just React JS. I like the Django admin page, and how simple it is. But I want to learn React JS. i have made few projects with Django, so I know how to use it.
You should use django if you need it
Ofc
im getting css errors from vscode about putting jinja2 in the style="" argument in HTML
an example of this is: html <img src="someimg.jpg" alt="Some Image" style="width:{{ 50 + 10 }}%;">
it runs perfectly fine but throws 3 errors about brackets
{% set n = 50 + 10%}
<img src="someimg.jpg" alt="Some Image" style="width:{{ n }}%;">
yeah
oh right
if i put anything in style="" if gives errors
i see lol
weird ๐ค
yeah
some css writing over it or smth?
did you try to turn it off and on again? ๐
cache ?
also is jinja supported in .css files
not that i'm aware off no