#web-development
2 messages · Page 48 of 1
That kinda site really isn't a good look for here. You can just give someone the answer and explain that they might have found it faster via Google thank asking here.
No need for passive agressive stuff like that or lmgtfy
Trying to construct a form with Django for testing, but it seems some fields get removed from cleaned_data and as result the code crashes; Note that I have limited experience with the current codebase as it's made by someone else at work.
...
File "/home/mart/git/****/digisof/forms.py", line 106, in clean
if cleaned_data[field] < min_value:
KeyError: 'number_of_lines'
@rigid laurel Sometimes, google gives you a more specific answer as I have no access to their css.
Why am I typing like I am drunk these days
@rustic pebble thanks for your help 🙂
😆
If i have a template ready and i want to edit it, is it better to use django-cms or django?
Guy can someone explain what it means to have relation on model level but not database level?
It means that you can to create 2 connected classes but not 2 connected tables
So can I use foreign key on username and user?
Sry is there any related material to read for this?
Any links? i don't understand what to search for.
Check Corey Schafer's explanation in databases @cobalt oyster
he got the explanation for it
So can I use foreign key on username and user?
@cobalt oyster yes u can as every user has a username
@native tide won't using foreign key connect tables?
Yes
It is valid you can do it but not recommended
just have 1 table for them
as every user gonna have 1 username
not several one's
It is a good practice to use it if like you have a user with several amount of posts
so you "link" those posts to 1 user
but 1 user gonna have 1 username so do not make 2 tables
Oh ok but won't that be primary key. Sorry I am asking too Many questions. Does the video you shred have answers to it?
Not having the relationship in the database is bullshit
That totally eliminates all referential integrity
@cobalt oyster
So the assignment I was given is faulty?
@tired root You can't judge professor assignments 🙂
It's at least not very sound
@rustic pebble I just did
Professors live in a very weird world of outdated knowledge with some current knowledge mixed in
That is why I told that
Its actually an assignment for internship post. Like first round of interview.
@cobalt oyster the video has answers
the User will have a primary key
yes
also ive come up with this. how do i make spaces between the images and display text under them so it looks clean?
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Hello, world!</title>
<style type="text/css">
.row div{padding: 20px 10px;}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-6">
{% for movie in movies %}
<img src="{{ movie.poster }}" alt="Movie Poster" height="260" width="175">
{% endfor %}
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
my code
I never used boostrap, but in this div <div class="col-sm-6"> in the css you can add a padding or a margin and it should normally work @native tide
to have the text under them, have in your {% for %} loop a <p> and pass in from python the text and then put {{ text }} in your html
can someone tell me how the hell human build this website? whats the toolss hows the animations works.. page transition.. everything is really blowin ma mind
open with chrome
Advice request! Can you help, or know someone who can? Details here: https://www.reddit.com/r/Python/comments/flkhm9/advice_request_re_pythondropboxbrowser_app_dev/?utm_source=share&utm_medium=ios_app&utm_name=iossmf
0 votes and 1 comment so far on Reddit
@pliant falcon Wow, it's beautiful on mobile too. That isn't really Python related as everything you see there is done on the front-end with JS and CSS, but it is an amazing looking site.
That website looks nice but holy shit the scrolling on desktop is terrible
@native tide thanks. And about your images.
You can use css 'margin-bottom ' to provide space on the bottom. But if you want your page to fit any zoom or or screen you might wanna use bootstrap grid.
@pliant falcon react components maybe.
That website looks nice but holy shit the scrolling on desktop is terrible
@potent idol you right but for me its only on firefox.. if I use chrome its smoothscrolling
from django.shortcuts import render
import urllib.request
import requests
from bs4 import BeautifulSoup
from collections import Counter
from string import punctuation
def frequency(request):
if request.method == "POST":
url = request.POST.get['site']
print(url)
r = requests.get(url)
soup = BeautifulSoup(r.content)
# We get the words within paragraphs
text_p = (''.join(s.findAll(text=True)) for s in soup.findAll('p'))
c_p = Counter((x.rstrip(punctuation).lower() for y in text_p for x in y.split()))
# We get the words within divs
text_div = (''.join(s.findAll(text=True)) for s in soup.findAll('div'))
c_div = Counter((x.rstrip(punctuation).lower() for y in text_div for x in y.split()))
total = c_div + c_p
list_most_common_words = total.most_common()
print(list_most_common_words)
return render(request, "wordcount/frequency.html", {})
def result(response):
return render(response, "wordcount/result.html", {})
i need to create a django app that will take url as input and count the number of words on that url and return the top 10 most used words
now i can enter the url on my first html page but i can't get the result to be displayed
can anyone help pls
ping me
im finished learning basic html now, im planning to learn html5 but then i found out there is html6 lol. So should go straight to html6 or html5 first?
i dont know any css or js too, im following sololearn course
wtf lol i think i got trolled?? there is no html6 atm... pls correct me if im wrong
with react (frontend) + django (backend), is it common for them to be in the same project (repo)? otherwise, how would i make a pipeline between them?
https://hastebin.com/kuwoniwuju.py
So I can't seem to save my form data into my database
anyone know why I'm having problems with my code?
I am following a course online made by Mosh Hamedani
he ask to do an exercise
where you need to make a function that takes to arguments
two arrays as arguments
the second argument will remove the items it includes in the first argument
for example:js let arg1 = [2,3,4,5,1,2,2,5,5]; let arg2 = [2,5]; except(arg1,arg2); output = [3,4,1]
so i did the exercise
my solution is different from his.
solution1:js function except(array, toRemove) { for (item of toRemove) { while (array.includes(item)) { array.splice(array.indexOf(item), 1); } } return array }
solution2:js function except(array, excluded) { const output = []; for (let element of array) { if (!excluded.includes(element)) { output.push(element); } } return output }
which one do you guys think is better? Your opinion.
one mutates the original array, one does not
that's right, so you would choose that one?
It depends
if you want to keep a copy of the original array then you shouldnt mutate it
you could assign it for example to a new variable
new_array = except(array, exclude)
How can I add " singing in with goole or other platforms " in flask?
Ily
I have the code from an old project here, maybe it can help you
Hey @sly canyon!
It looks like you tried to attach file type(s) that we do not allow (.txt). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .m4v, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg, .md.
Feel free to ask in #community-meta if you think this is a mistake.
I have the code from an old project here, maybe it can help you
@sly canyon Please give it to me :O
Thanks !
hi, someone know about catch har file from python ?
What are the most important phones on this list in terms of making sure design is best?
I dont use smart phones so its hard for me to care about them. The only reason I do is because its expected and I dont want to seem lazy or unable to do it.
Fuck...
I just realized that my logins are not working in Chromium. :/
I'm thinking about quitting webdev.
Like, who puts up with this for fun? Why dont I just make programs for an operating system where I dont have to deal with this?
Webdev is fun until it turns into and endless cycle of compatability for this browser, that form factor
And its just like... why. Why make your program this way?
The only reason that makes any sense is because you can reach a lot of people and make a lot of money potentially. But thats not my end game. So I ask again, why should I torture myself with this bs
Its fun until you realize it only works from the scope of the thing youve been developing it for. Then as soon as you try it somewhere else and find it doesnt work all that fun just spirals down into...
"This is the complete opposite of fun."
@native tide are they erroring out on chromium browsers?
It just doesnt login. It doesnt flash the messages. It accepts the user and password but it just refreshes the browser.
I'm kind of too upset right now to calmly solve it. I have to destress from realizing that its doing this and fix it when im less dramatic about it
@app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('home'))
form = LoginForm()
if form.validate_on_submit():
user = UserAccount.query.filter_by(email=form.email.data).first()
if user and bcrypt.check_password_hash(user.password, form.password.data):
login_user(user, remember=form.remember.data)
next_page = request.args.get('next')
return redirect(next_page) if next_page else redirect(url_for('home'))
else:
flash('Login Unsuccessful. Please check email and password.', 'danger')
return render_template("login.html",
title="Login",
form=form)
oh shit
you should use redirects
instead of rerendering the whole page
so
you should do:
Theres a weird if statement there that does nothing
maybe thats it
I didnt finish that last night
I hope thats it
no nevermind
Thats not it
res = make_response("")
res.headers['location'] = url_for('whateverurlyouwant')
return res, 304
304 is the code for redirect
So for instance, when a user is logged in you want to redirect them to the logged_in html
I have never seen flash actions, I always use js to do it
It works fine in firefox. I dont really understand how to figure out why it doesnt work in Chromium. Its not something ive ever done before. It has to do with validating because its never getting passed if form.validate_on_submit(): and going straight to return render_template("login.html")
can you open the browser console and see potential errors?
good call Unchecked runtime.lastError: The message port closed before a response was received.
I can probably find the answer by searching this error
its being caused by chrom extentions!
Which...
in my case
I never use chromium unless I need some weird extention they dont have on firefox.
So my chromium has a lot of othem
Thats so weird
Hmm
Well thats what this stackoverflow question is saying i havent verified it will fix it yet
Fuck though.... Im really, seriously considering quitting webdev. I do this for fun, not to serve ads and get rich.
Like why would I choose a platform that ultimately is just constant compatability problems across different software
This is a real question im asking. Why would I do this? lol
Originally my thinking was, "It will be easy to reach everyone no matter what they are using."
But is it really though? Is it not actually just a nightmare of compatability adjusting? Do you eventually get better at making sure it works on everything before moving forward?
Or is this what webdev consists of entirely? Because thats what its starting to seem like to me
And I have to ask, why would I choose this for my hobby when I can make a program that works univerally on the same system I designed it for and maybe not everyone would reach it... But it would be a lot more fun for me to build.
It seems like the only justification for webdev is serving the shit out of ads. Tell me Im wrong so I can keep working on this lol.
Well, I got rid of that weird error which was to do with extentions
But it wasnt what is making my logins not works
It is something that gets better. Honestly, login is one of the trickiest things out there to get right out of the door. I've actually found that a server-side rendered login page is almost always best, because if you have to do something later like support SSO it's a lot easier to go through the redirect flows there than it is through Javascript/React/Some API you've designed.
Even if the rest of my app is 100% React/GraphQL/API based, the login page is almost always a traditional MVC server-side throwback to the late 1990s / early aughts.
As for the stuff about smartphone layouts you asked about earlier, start with Bootstrap and use its layout mechanism heavily until you need to get fancy with it. That'll solve 90% of your headaches and cause only around 20% on its own.
Yeah, its mainly when I add elements too the bootstrap templates that it starts to be a headache. That is at least a headache I know how to solve.
This is entirely new. That is: Works 100% in browser 1, does nothing/no feedback in browser 2
Right now Im trying running on different ports.
My login is 100% flask/flask_login
I complain and say that I will quit.
But I calm down and I will be back at this shit again and again.
Thats who I am
Well web development can get really annoying really fast, but web dev is way more fun compared to regular program development. I love it because it incorporates many technologies together
Damn...
The thing is, this isnt JavaScript, so there arent errors in the console relevant to this.
Its not erroring, its just not doing what its supposed to do.
And if it is what its supposed to, that doesnt explain why it does a completely different thing in another browser.
So... where do you even start to look.
All I can think is to keep googling, "Flask_login works in firefox not in chromium" and try everything I find
But so far nothing
Im gonna try broadcasting the dev server on 0.0.0.0 so i can use chrome on another device and see what happens.
Im very curius to see if the same behavior happens in Windows from chrome but I dont have a windows machine unless I shut down this OS where the dev server is running from.
It has to be this! lol. The pitfalls of being a privacy nut. I hope this is what it is
I should get a Windows VM set up.
I don't think it is that
judging from what you sent me earlier you are not using cookies at all
That is what it was.
Actually?
Yep. It logs me in now
I need a message that tells users they cant block cookies I guess :/
The only reason I block cookies is third party cookies that are so common
For this domain and port.
Oh well
I never use chromium at all really. I have it just because I have it.
Is bootstrap only used for prototyping and stuff?
Or is it actually used for production?
Its used in production
@rustic pebble I'm being thrown like 20 errors from flask and don't even know where to start to look up online the cause
So basically it is not able to locate the index.html file
Could you send me the codeblock you are currently experimenting on?
from flask import Flask
from flask import render_template
app = Flask(__name__)
@app.route('/')
def index():
greeting = "Hello World"
return render_template("index.html", greeting=greeting)
if __name__ == "__main__":
app.run()
that file is app.py
<html>
<head>
<title>Gothons of Planet Percal #25</title>
</head>
<body>
{% if greeting %}
I just wanted to say
<em style="color: green; font-size: 2em;">{{ greeting}}</em>.
{% else %}
<em>Hello</em>, world!
{% endif %}
</body>
</html>
that is index.html
So for starters 2 things
If you want syntax highlighting like this:
def example():
print('this is an example:')
you should do:
three_back_ticks``python
rest of your code
!code
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!')
```
Note:
• These are backticks, not quotes. Backticks can usually be found on the tilde key.
• You can also use py as the language instead of python
• The language must be on the first line next to the backticks with no space between them
This will result in the following:
print('Hello world!')
Seocnd, when importing from the same module you should do
from modulename import 1,2,3,4,5
in your case
from flask import Flask, render_template
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
greeting = "Hello World"
return render_template("index.html", greeting=greeting)
if __name__ == "__main__":
app.run()
so Ok
<!DOCTYPE HTML>
<html>
<head>
<title>Gothons of Planet Percal #25</title>
</head>
<body>
{% if greeting %}
I just wanted to say
<em style="color: green; font-size: 2em;">{{ greeting}}</em>.
{% else %}
<em>Hello</em>, world!
{% endif %}
</body>
</html>
Where have you put your index.html file?
index.html is in templates folder, app.py is in gotonweb folder
Following my tutorial which might be outdated/bad
Yea you should move the app.py one file app
you should have app.py next to the templates folder
wow, the tutorial didn't tell me where to put app.py so I just assumed a place which was wrong
Did it work?
yeah except I think my html file is broken
wwdym?
oh nevermind, I just didn't understand my tutorial xD
If you have any questions tell me
I have a newbie question
Shoot
soooo I have learned Python, HTML5, CSS and good bit of Javascript, if i wanted to build a portfolio site to showcase my work to employers, where should I start with back end? I can put in the time to make a full front-end by myself I just don't understand how hosting works, domain names and what it entails to make the website an actual website that anyone can go to
I have no clue about domains but look into the python flask library
I'm just an overwhelmed cookie over here doing this all on my own
There’s a lot of tutorials like a lot
It will tell you how to use the flask server to serve your HTML, css and JS to the web
The one Tech With Tim does teaches you how to host it so everyone can see it at the end of his tutorial
I've messed around with flask a bit, I'll look into that, I know flask uses templates to make identical pages, is Tech With Tim a youtube channel?
Yup
If you need help deploying website then you should ask on #414737889352744971. If you need help creating one ask here
Well basically you need to have a server that serves the correct files on user request
if ur web page is static i mean server sided scripts are not even needed xD
Yup
I just looked up Tech with tims youtube channel and it's perfect and has a lot of content thank you I didn't know about him before
I've run into an issue when setting up test script for my app.py, unable to import 'nose.tools pylint(import-error) do I have to install nosetools/nosetests or something?
Wouldn’t be a bad idea to try
oh boy that made a different problem xD
Rough
just a lot of unused imports does that affect anything?
I’ve never done any testing with test modules or stuff like that but in python no it shouldn’t be a problem
@rain goblet watch ur app structure or what ever sometimes it can cause trouble , keep the test at root
I am not using linux or virtualenv and I am just following a tutorial
Hello, community,beginner here. I have a question and would really like some guidance on a web application I want to make. It has to do with a user uploading an image. The image is then prompted with several recommendation of background templates or images,( 2 or 3) . My question is. how do you go about storing these background templates/images. I understand it would require building some sort of databse or filesystem.
There are many ways
The easiest one is to convert the image to base64
send it over through http
reparse it to image on the server
and do the calcs there
@rustic pebble wanna help me again? xD
@rain goblet sure, whats ur issue
fwiw, that probably wasn't flask, but was your browser cacheing the static files
There is an option in dev tools to disable caching
To fix it, somewhere in the Chrome/FF dev tools, there's a tick box somewhere thats something like "Don't cache static files when dev tools is open"
^
hello y'all, could someone of you have a look at my flask problem in #help-chestnut ? I'd be so grateful for help...
hi how to integrate botui with WebSockets?
I can receive data from server
but I have issue with sending data to server
@rustic pebble GOOD NEWS
I was able to solve that problem of having to submit the form twice
Withou FLASK-CORS or Javascript workarounds
Well, I did so much stuff that I'm not exactly sure what was the minimum necessary to achieve that
But basically I got rid of SERVER_NAME on my environment variables, as well as host parameters on my routes, when I've initiated the app I also got rid of host_matching=True as well as static_host='myapp.herokuapp.com'
I've also eliminated url_for(... with _external=True on my contact_form.html, it's now just <form method="POST" action="" novalidate>
But more importantly, I was forgetting to import my environment variables inside my create_app function that heroku requiers
init.py ( root/app )
from flask import Flask, request, current_app
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
import datetime
from config import Config
db = SQLAlchemy()
migrate = Migrate()
# Heroku
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
db.init_app(app)
migrate.init_app(app, db)
from app.main import bp as main_bp
app.register_blueprint(main_bp)
if not app.debug and not app.testing:
# ...
if app.config['LOG_TO_STDOUT']:
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
app.logger.addHandler(stream_handler)
else:
if not os.path.exists('logs'):
os.mkdir('logs')
file_handler = RotatingFileHandler('logs/ladingpages.log',
maxBytes=10240, backupCount=10)
file_handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s '
'[in %(pathname)s:%(lineno)d]'))
file_handler.setLevel(logging.INFO)
app.logger.addHandler(file_handler)
app.logger.setLevel(logging.INFO)
app.logger.info('Lading Pages startup')
return app
from app import models
maxiimoveis.py (root folder)
from app import create_app, db
from app.models import *
app = create_app()
@app.shell_context_processor
def make_shell_context():
return({
# Database
'db': db,
# Classes
'User': User
})
Procfile (root folder)
web: gunicorn app:app
web: flask db upgrade; flask translate compile; gunicorn maxiimoveis:app
I'm running few more tests, but I know for SURE that it was a problem with the CSRF validation
They were not matching
So I have deactivated it temporarilly, but I'm activating it again to see if flask-cors is really needed or if I can solve it with WTF_CSRF_SSL_STRICT=False
Indeed, not even WTF_CSRF_SSL_STRICT=False was needed, I have activated CSRF again and it's working just fine
Hey, is there any way to check varible inside jinja template?
@abstract ridge check for what?
@sly canyon varible type i mean
@abstract ridge I don't think you can receive the variable type, but you can test if it is a dict, string
or int
I think
ye,this exactly what i need
@sly canyon Ty very much 💙
NP
ok hey guys. somebody help me setup something cool with python+django. i want to create a backend with a database connection of somekind and create an interactive frontend where you can drag sliders and stuff, so that it queries for new calculations from the backend dynamically, at least.
hm
i have no idea what tech i want, i just know i know python the best.
heh
I'm picturing a simple drawing program
let the user draw circles, squares, triangles &c
it's probably gonna involve data science and stuff but something of that kind yes
where changing parameters of the models will be recalculating lots of stuff in the backend and spits you out new things
interactively you'll update the screen to show them what their drawing will look like as they (e.g.) drag a square around, or change its size.
the db part will be to save the drawing for later
hmm
so wait i need to really think about whether i even need two-way connections actually here
since the get is always simple
what I described would probably require a two-way connection between the user's browser and your web service, but not between your web service and the database
and it's not like post is much harder but it needs a separate endpoint
yeah
well the DB is hidden anyway (and I guess any DB connection is 2-way?)
@quasi ridge what tech would you choose
I'd probably use dynamodb for the backend, since I'm somewhat familiar with that (not because it's the best tech; I dunno what the best tech is). Similarly I'd probably use Pyramid for the web framework
I built https://teensy.info with those and it works well enough
flask might be a better choice of framework since it's a bit simpler. I can't remember why I chose Pyramid, tbh.
@native tide It really sounds like Django might not be the best for what you want. Flask+ReactJS on the front end might be better
it sounds like the core of your app is pretty interactive
whereas Django is more oriented around a static frontend
Hi guys
is flask really meant for anything serious?
I thought it's kind of a joke meant for only prototyping
@native tide is Netflix serious enough?
so me and my group wanna start doing a group project (web development using flask) can you give us any project ideas for beginners
@sly canyon they use it?
@native tide Airbnb, Netflix, Reddit, Patreon, Uber, Samsung, Nginx ...
like the same version you can install with pip or do they have some in-house versions of it?
I'm pretty sure none of them use it. But it can be used. The way they scale it is by running lots of instances of the same Flask application
and then load balancing between them
But Flask is used a lot in enterprise
a lot of what you're doing is data vis it seems, and thats perfect for Flask
Flask is also used to expose ML models via an API fairly often
Should I be worried about initializing my app a certain way
yes.
What would be the correct way?
beats me! I was being sarcastic. To spell it out: I have no idea what you're talking about and thus cannot possibly answer.
How easy is HTML to pick up? If I wanted to be able to create basic webpages
Pretty easily
Easy*
And css is easy too and jf you know python JavaScript is not hard at all
@ebon gull not that it matters about the time limit
If I were to put in 1 - 2 hours of learning HTML per day
How proficient in 2 - 3 weeks?
I will learn CSS after then focus on Django, not concerned with JS. Aiming for backend
Depends how good you use your time I sat down and learned HTML for about 4 hours and then was able to google things as I went super easily after that
Thanks
@native tide https://philip.greenspun.com/panda/html
soooo npm is broken on my mac and i can't seem to fix it
Have you tried turning it off and on again - IT Crowd
semi-serious
uninstall & reinstall?
why do we have to be like this.... it's a legit question that is not easy to fix, do you think i've already tried that, yes i have
I have no idea what you may have tried, sorry
if i ask dumb questions just say it's a dumb question
people of all levels ask questions here
it's not a dumb question
and the sad truth is that reinstalling often does fix things, which is why I suggested it
true honestly
in any case I know zero about npm, so other than my basic suggestion, I don't have any ideas
anyone know if the speed enhancments of the quart framework matters when you end up hosting it on something like linode using apache
speed enhancments over flask to be percise
What is broken about it @spring rampart ?
And have you tried uninstalling and reinstalling?
someone ping me if they have some insight
@rigid laurel it has to do with npm not being able to find a config fil
Lemme link a picture hold up
i already tried brew uninstall npm, didn't work
it throws a error like this
Error: No such keg: /usr/local/Cellar/node
@spring rampart did you try brew uninstall --force?
also, crazy as it sounds, you might brew install node first, and then try to uninstall npm
anyone have any gripes with Quart seems like it does everything flask does with the same lines of code it just runs faster
please ping me
@ebon gull yes it is technically faster flask that supports async
is there any reason to continue using flask or should all future projects be done with quart
i think i've seen somewhere in quart docs that it supports most of flask extensions
i wonder why its not more popular then it seems great
@ebon gull if you really want to dab into async and try to do performance optimizations, quart is a nice framework
i wonder why its not more popular then it seems great
yes, it feels great
it's only weakness is that noone knows about it :p
I know its crazy it seems like a no-brainer to use it over flask worst case scenario your app runs the same speed as a flask app would but it can use HTTP2
How should i host my flask project? When i try to host it on pythonanywhere, my code cant connect to th external mysql database. The database rejects the connection.
Many options depending on your requirements. See if heroku works for you.
The problem is that my msql server rejects the connection. Is there a solution for that? Like a local database or so.
where is you mysql database located?
Can you show the code with which you connect and the error you are getting? Please do NOT show database password.
mydb = mysql.connector.connect( host='remotemysql.com', user=''********', passwd='********', database=''********', connect_timeout=False )
Getting always the error code 110 i think i dont have anymore the error logs
Hahaha you got me had to change that
@native tide when i am connection from my laptop using pycharm there i no connection issue, the problem only appears when i try to connect from a hosting site
are you sure it's the server rejecting the connection? Maybe, instead, it's the client being unable to connect to the server
if you have access to the server logs, you might be able to see some information about why the connection was rejected (if it indeed was)
And if you don't, just briefly try heroku, it's free and takes like 5 minutes.
yeah the server logs showed me that the connection gets rejected
i will have a look on heroku i used it months ago for a project but not for flask
odd that the logs don't tell you why
idk because i dont have them anymore
Yes, please read up on Flask and Django and then come back for specific questions.
Also try quart it’s flask but faster uses almost the same syntax
Hi I'm working on a blog site and I'm trying to set up password reset email but I'm getting this error Ik its some gmail smtp error but I don't know how to configure I wanna configure it for every user not only for me. So here is the error :
(530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError d4sm5789701lfa.75 - gsmtp', 'webmaster@localhost')
Request Method: POST
Request URL: http://127.0.0.1:8000/password-reset/
Django Version: 3.0.4
Exception Type: SMTPSenderRefused
Exception Value:
(530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError d4sm5789701lfa.75 - gsmtp', 'webmaster@localhost')
Exception Location: C:\Users\Usman Fazal\AppData\Local\Programs\Python\Python38-32\lib\smtplib.py in sendmail, line 871
Python Executable: C:\Users\Usman Fazal\AppData\Local\Programs\Python\Python38-32\python.exe
Python Version: 3.8.1
Python Path:
['E:\\Python\\django_project',
'C:\\Users\\Usman '
'Fazal\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip',
'C:\\Users\\Usman Fazal\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs',
'C:\\Users\\Usman Fazal\\AppData\\Local\\Programs\\Python\\Python38-32\\lib',
'C:\\Users\\Usman Fazal\\AppData\\Local\\Programs\\Python\\Python38-32',
'C:\\Users\\Usman '
'Fazal\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages']```
and here is my setting.py file source at the end I've added my Email configurations: https://paste.pythondiscord.com/raw/masejevoyi
I asked this question in help-3 but my question was being ignored so I'm asking here.
To send an email via gmail you need special authentication beyond what I assume smtp.EmailBackend gives you
I know that thunderbird and other mail clients had to work in special functionality to allow you to access/send mails through gmail
so what you think I should try a less secure mail system?
If you've looked at the specific error message, you'll note there's quite a bit of detail in the help article you linked about attaching applications to your gmail account
hmmm I tried gmail
I would suggest that, you're likely to also trigger antispam in gmail and that could do unpleasant things
Historically I've used mailgun, they've got a pretty simple interface for these things, but I've not actually researched it
And it's a paid solution
I checked this https://support.google.com/mail/?p=WantAuthError d4sm5789701lfa.75 - gsmtp provided help link and I got some Google app password stuff I tried but It didn't work for my own provided mail address and if it'll work then its not going to work for random people
you're trying to send an email as webmaster@localhost and also trying to log that account at gmail?
show us your send email function code
@native tide
#...
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import email.utils
# Support for asynchronous email sending so that the application
# can continue running concurrently with the email being sent.
from threading import Thread
# Asynchronous email sending implementation
def send_async_email(app, msg):
with app.app_context():
# Sending Email
server = smtplib.SMTP_SSL(host=current_app.config.get('MAIL_SERVER'),
port=current_app.config.get('MAIL_PORT')
)
server.set_debuglevel(False) # Deployment version or Testing Version?
server.login(current_app.config.get('MAIL_USERNAME'),
current_app.config.get('MAIL_PASSWORD')
)
server.sendmail(from_addr=current_app.config.get('MAIL_USERNAME'),
to_addrs=msg['To'],
msg=msg.as_string(),
)
server.quit()
def send_email(to_addrs, subject='', text='', html=''):
# Create message container - the correct MIME type is
# multipart/alternative.
msg = MIMEMultipart('alternative')
# Author
msg.set_unixfrom('My Web App Name')
if type(to_addrs) is list:
msg['To'] = ','.join(to_addrs)
else:
msg['To'] = email.utils.formataddr(('Recipient', to_addrs))
msg['From'] = email.utils.formataddr(current_app.config.get('MAIL_DEFAULT_SENDER'))
msg['Subject'] = subject
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message,
# in this case the HTML message, is best and preferred.
if text:
msg.attach(MIMEText(text,
'plain',
current_app.config.get('MAIL_DEFAULT_CHARSET')
)
)
if html:
msg.attach(MIMEText(html,
'html',
current_app.config.get('MAIL_DEFAULT_CHARSET')
)
)
Thread(target=send_async_email, args=(current_app._get_current_object(), msg)).start()
if that helps
Some of the environment variables I use:
# Flask Email SMTP server settings
MAIL_SERVER=smtp.mydomain.com
MAIL_PORT=465
MAIL_USE_SSL=True
MAIL_USE_TLS=False
MAIL_USERNAME=contact@mydomain.com
MAIL_PASSWORD=somepassword
MAIL_DEFAULT_SENDER=My Web App Name,donotreply@mydomain.com
MAIL_DEFAULT_CHARSET=latin-1 # Because we speak PT-BR here.
I'm working with PaceJs, and I want to show a loading bar when a button is clicked.
The bar shows normally when the page is loading.
problem is :
The button runs a python script , and the loading bar is being showed after the script finished .
I want to show the loading bar during the script execution which takes a while to finish.
@sly canyon Dude I'm trying to make a reset password function So when the user request for reset password he'll get a password reset email
I know that, what you have not shared is how are you trying to accomplish that
And what I've done is showing how I do it
I have a checkbox named terms, and need to check if its been checked or not (using flask and python)
this si what I have so far:
terms = request.form.get("terms")
if name and addr and items and phone and terms:
# do stuff
else:
#do other stuff
however, when the box is checked, the else executes
how do I check if its "checked"
@weary acorn but have u defined name, addr, items, phone and terms?
form.data.name , form.data.addr, .... ?
not sure if this is where i need to go for this, but i have text that i need to upload to my 000webhost website using python, is there any apis or something that i could use to change the html code of the site using python?
any other host where I can easily access the text is fine, if that host doesnt work
@urban spoke you could prob use this https://docs.python.org/3/library/ftplib.html
but I feel like setting up a proper web server with an API would probably be better long term
but idk your application
just doing some testing and messing around
I'm working with flask-wtf and I want to display form validation errors using jinja macros.
https://flask.palletsprojects.com/en/1.1.x/patterns/wtforms/#forms-in-templates
Even copy/pasting this example returns an error: "TypeError: 'HTMLString' object is not callable"
Can someone help me deal the following issue. I am on Django, just started learning it. Basically the following part is creating recursion errors for some reason.
RecursionError: maximum recursion depth exceeded while calling a Python object
Could someone take a look on it and maybe give me a hint?
https://paste.pythondiscord.com/sucocacilo.py
It is practically empty
That's.. interesting
Are you sure that file is the source? It shouldn't be. What's a chunk of the traceback look like?
Oh ok. I am kinda lost with Django. Flask, aiohttp are straightforward
Yeah, django is a framework with it's own ideas about organization
I mean, on it's face it's fairly simple
Yea it seems ok
you add a url(pattern, view, name) entry, but I'm not sure what you did
I did that:
Is this within IdeaParadise.urls.py?
wdym .py?
fing autocorrect
So basically this is my file structure
Ah, yeah
Say I want to create a route which renders a home.html file
So, that urls.py file is also known as IdeaParadise.urls
so you're including the file within itself
How would I got about it?
oh ok
Say I want to create a route which renders a
home.htmlfile
Could you kinda walk me through this?
Once I am able to do one route, I will figure out the rest, rough start
I had made one and I deleted it, but it looked something along the lines of
def home(request):
return render(request, 'IdeaParadise/home.html', {})
That was inside views.py should I recreate it?
yes
Generally, you have a "view function" that does the actual rendering and is inside yourpackage.views, your urls file them imports that via .views, and then registers inside the urls via url("/", views.view_name, name="debug_name")
I am kinda confused as to what mypackage is
There are two packages named the same
right. So your manage.py is.. well.. manage, your IdeaParadise project is IdeaParadise. The urls file inside IdeaParadise is IdeaParadise.urls
If you were to put a file inside that second IdeaParadise folder, it would be IdeaParadise.IdeaParadise.filename
Oh ok
So say I wanted to render a home html file
How would I go about it?
I created the view
Right, now you go to your urls file
Sure
and you import your view at the top, then add it to the urls list like I showed you above
I do this by doing: from . import views correct?
yep
Hm, okay, done
url("/", views.view_name, name="debug_name")
Means "at url /" use the function "views.view_name" and if someone wants to find the function it's called "debug_name"
And then it should work, mostly
provided your view is setup with templates and etc
oh ok
This should work right?
urlpatterns = [
path('admin/', admin.site.urls),
path("/", views.home, name='home')
]
yep
yep
This should be my current setup
yep
Your render() function I'm not sure if it will
Hm it launched
progress
Ok
sec
Btw where is my view leading to?
def home(request):
return render(request, 'IdeaParadise/home.html', {})
We are getting somewhere
that render call means "render request with template 'IdeaParadise/home.html' and no data passed to the template"
I think just home.html instead of IdeaParadise/home.html may work
Let me try
There's a whole template loading thing that goes on with many locations and targets and complexity
Same error
There should be, down below, a list of locations it's searching
Yeah, so this part:
Django tried loading these templates, in this order:
is the important one
You'll note it only searches for files in djangos admin locations
In your settings.py file you should have templates configuration
Looks something like this:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
'/home/html/example.com',
'/home/html/default',
],
},
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'DIRS': [
'/home/html/jinja2',
],
},
]
You'll either want to enable APP_DIRS, which you should only use if you're not concerned about relying on any missing-template-fallback-behavior, or you'll want to add your directory to the list
Here:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
# ... some options here ...
},
},
]
So, right after "dirs"
Mine is not exactly the same
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
As it seems
What's your installed_apps look like?
Where can I see that?
It's in the settings.py file as well, usually further down
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
Yeah, you need to add your app to that to
It's IdeaParadise like we mentioned before
No, just IdeaParadise
let me try
That tells django that there's a django app called IdeaParadise, which it should load, models, views, urls and all
It worked!
of course
TBH most of django is knowing where all the little pieces need to be put for it to find them
Yea, I don't rly like that tbh
But I am not doing the project alone it is collab work
How might I be able to pass two variables through a redirect() in flask?
Curiosity question for folks out there...
Why do you think flask ended up being so much more popular than bottle for simple/small projects?
@surreal heart Variables? What are in these variables?
@timid frost Probably because according to the site ( https://bottlepy.org/docs/stable/ ) it's at 0.12 , and Flask is more mature.
@native tide bottle has been at that number for a long, long, while... and flask was too. IIRC, they suddenly 'jumped' the version number to tweak that perception (relative to other options, but still).
https://bottlepy.org/docs/stable/development.html - Them still having a G+ on their development page doesn't bode well.
But regardless, I don't use Bottle nor have an interest in it. Just throwing possibilities out there 😄
Do you honestly think the average person doing a small project on a RPi looks at that kind of stuff?
Just seems like there's this automatic reflex recommendation of flask for everything...
Hella good marketing, however it happened 👍
It's not marketing, though. Flask/Django are the goto for good reasons.
@native tide Definitely. I have been lately working with AWS Lambda (Serverless Arch) though. Seems like just simple python functions are also damn good in Serverless arch. I have heard people using Flask (and even Django) on Lambda. It kind of doesn't makes sense to me.
Flask is really easy to bring up and doesn't force anything on you
Django is slick and has a lot from the get-go
Last I checked bottle isn't vey actively maintained and it still seems to be the case
232 issues, 50 PRs. Looks like it hasn't seen particularly many commits since the end of 2016.
@proper hinge I think that may be the thing, right there. Isn't bottle almost a one-person show?
I don't know
I wouldn't want to base my project on an ostensibly inactive library and I'm sure many others feel the same way
That's another thing, is not depending on something big like that with very few maintainers
Again I wasn't thinking so much 'project' in the sense of the "Next Big Thing", but all the myriad small one-off projects for nobody but yourself.
And even 4-5 years ago, everyone was chanting the 'flask flask flask FLASK' mantra... the bottle dev might have just finally given up since then.
Both projects are at least a decade old. Maybe a long time ago Flask was better? I wasn't around for that so I don't know. I think once a project picks up in popularity, even by "luck", then it can become a chain reaction: more resources, more use in production thus better reputation, bigger community, etc.
👍
There was a great blog post about various web frameworks in Python but I can't find it
😦
The author was looking for a framework to use and laid out some criteria, then compared them
He made a point about bottle not being maintained actively so I was reminded of that article
Cool. Interesting that his final choice was something that I've never heard of - but then, I don't really follow that stuff too closely, either.
I ended up going with Falcon too after reading this
Was debating between Falcon and hug, and in hindsight hug would have been simpler code since the project barely had any endpoints
Japronto looks cool too
Gives you a perspective of just how many frameworks are out there
Mind you, this blog is 2 years old so there's probably even more now
Excuse me, I wonder if someone can tell me if I'm on the right path with this; trying to run a python script on a website domain
running on EC2 instance and a route53 domain
My approach was to have the .py script in the home directory of the instance, then set the value of the domain's record set as the EC2's IP address. Is this the right path?
I can barely understand what you're saying
explain like I'm five: what problem are you tryign to solve?
don't tell me how you're solving it; just describe the problem
I feel like that's a bad sign for my approach 😅
"I want to find prices for sneakers on the web" or something
oh okay
"I want to annoy the British Ministry of Defence"
"I want to ensure my web service is healthy"
I'm intrigued by those possibilities but namely, I want to be able to run my flask app on something other than localhost
you mean, have it listen on a "real" IP address?
that should be as easy as changing "localhost" to "0.0.0.0" somewhere
more specifically, a website
now hold on
a custom domain
it's running on my laptop
ok
do you have access to a "real" machine? Like an ec2 instance, heroku thing, google cloud, azure, etc?
yes I have an Ec2 instance running with the script in its home directory
ah ok
can that EC2 instance receive traffic from the Internet? Like, does it have a real IP address?
I think mine has an "elastic IP address", which oddly enough is free
rare that anything in AWS is free, but real ip addresses seem to be
have you configured your ec2 "security groups" so that port 443 is let in?
I've allowed ports 5000, 443, 80
I think you have to do that explicityly
and 22
ok so you're 90% of the way there
so ... what isn't working 🙂
(btw I do exactly this -- https://teensy.info is just a script on a single ec2 box)
I use pyramid, not flask, but that shouldn't matter
it wasn't that hard actually
and I don't know (&(&( about front-end stuff
Well trying to connect the pieces together is giving me some trouble
well be specific
I wonder if it's just the format of my code, and it's something silly
tell me what you're doing, what you're observing, and how that observation differs from what you expected
quick question: for teensy, do you have everything in a directory in the ec2 home dir?
not everything no
I think I use nginx for the ssl stuff, and it lives ... wherever it lives
hmm
tell me what you're doing, what you're observing, and how that observation differs from what you expected
I just have the init.py file sitting in the home dir
The instance seems connected to everything, it's running,
ok you're talking very very vaguely
I was hoping more for "I typed flask run and it responded with HTTPError: you're ugly or something
lol
Until you get specific, I can kinda sympathize, but I can't actually help
yeah that happens too 🙂
darn, nevermind.
so, when i type flask run, it runs on the localhost, but isn't accessible thru the domain name
Running on http://127.0.0.1:5000/
ok, so you need to tell it to listen on the real IP address
that might be something you can do with an argument to flask run, or it might be something you need to do in your code
I don't use flask so I don't know off the top of my head, but I'm 98% sure it's trivially easy
$ python3 -m pipenv run flask run --host 0.0.0.0 --port 443
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://0.0.0.0:443/ (Press CTRL+C to quit)
hm, permission denied when i added --port 443
but just flask run --host=0.0.0.0 runs
yeah that's because Linux is stupid; you need to be root to "listen" on any port whose number is < 1024
try another port, or try it with sudo
I'm guessing you're using a reverse proxy ... maybe even Squid 😁
in which case you won't need flask to listen on a "low" port; you can let it hang out at 5000 or whatever, and have the reverse proxy do the listening-on-the-low-port thing
or there might be a way to have ec2 fiddle the ports around for you
I was hoping to have my ports fiddled by ec2
man, i need to learn about networking
Okay, will try some things and report back
thanks for being the 🦆
I need to learn about networking, too; one of these days my co-workers will realize that I don't understand it
fwiw, I don't do any such fiddling; I tell EC2 to let port 443 in, then I run nginx as root, listening on port 443, and forwarding the decrypted requests to port 8080

it's true!
looking into nginx
what?!
srsly did you not know there's a popular reverse proxy called "squid"?
I just assumed you'd be using it 🙂
you only need nginx if you're doing SSL, or if you expect to get a lot of traffic
Oh,
(or if you hate the idea of your miserable python code running as root)
Looking into squid
I don't know how good squid is; I just know it exists. Might be unmaintained these days
yikes, http://www.squid-cache.org/ has a seven-year-old timestamp at the bottom. I'd stay away.
Oi
nginx is the real deal
people actually use it out in The Real World, and for simple cases it's fairly easy to use
Well this is a small little project so idk if I need a reverse proxy
you may well not
I'd forget about it until you really need it
no need to make your life more complicated
I only use it for the ssl -- I am always complaining about other sites not using ssl, so I figured I oughta have my site use it
oh , I never installed apache webserver
I think that's it
wait, Elastic Beanstalk??
This is shooting mice with artillery
squid is a webcache for professional setups
If you want to set up a flask app on a webserver, use a wsgi server and a reverse proxy, apache or nginx, to not expose it to the web
or use mod_wsgi on apache
@earnest oak
either is fine
I am looking into Elastic Beanstalk now, as that seems to take care of some of the network stuff for me,
but yes, I should look into mod wsgi and apache next
I looked at EB once years ago and fled, screaming, from the room 😐
insanely complex, terribly documented
YMMV
I figure I should rewrite teensy.info to use "appliation gateway" and lambda; I'm not sure what "application gateway" even is but I suspect it would do what I want
Do you need to know HTML to learn Django? How much HTML / CSS knowledge is required to be a backend developer?
a) probably a little; b) a little 🙂
I'm a backend dev and I know the basics, but that's it
other than helping out with some web site that nobody officially owns, I've never actually had to write html
I have a basic portfolio written in Django and I only know the very basics, I used pre-built html things mostly - there is a name for them but I cant remember it rn
@quasi ridge what do you mainly do?
What are some things you would suggest someone wanting to get started in backend development to learn? If they wanted to start off with Django.
I maintain (and very rarely get to improve) an internal web service, and a bunch of associated stuff, that helps automatically fix network problems
there are ... I think ... six of us on my team
Django is probably a good start. Make sure you can deal with a reasonably-complex database schema -- a few tables with foreign keys, etc
if I were you I'd learn about scale -- what happens if your traffic goes up by a factor of ten? What happens if your database disks fill up?
Yeah, I’m planning on learning SQL (PostgreSQL) over the summer.
When it comes to learning about scale, where are some good resources to learn this?
PostGres is a good choice, probably the best open source DB there is
well I'm biased; I'd say learn a couple of AWS (or equivalent) services
dynamodb, sqs, and sns are reasonably straightforward, once you get over the hump of users and permissions and stuff
then there's RDS which is your old familiar database, except you don't have to do much to administer it
except pay AWS money 🙂
Noted.
When it comes to learning about scale, do you have some resources on hand that really helped you understand it?
How would I be able to simulate learning about scale?
As in, I can learn the theoretical concepts, but I don’t have a project that had many users.
set up the most underscaled, underprovisioned system you can manage, then stress it until it breaks
I've never done this btw
How did you go about learning it yourself?
run it in a leetle teeny VM maybe
I learned mostly by being thrown into the deep end.
I had a job where we hosted everything ourselves, had individual databases, and then changed jobs to work at a well-known cloud-services-provider, where scale is everything
This is not a question, nor a discussion topic rather it’s a statement. Use quart instead of flask I feel like it is a under appreciated framework. It is compatible with flask works almost exaclty the same but is faster out of the box and supports http2
Instead of Flask(name) You use Quart(name) add a couple async words before your functions and your off. Because of this I would say it’s objectively better then flask it can even use some of flasks extensions that is doesn’t natively include
Even the flask documentation will work with Quart with very little modification
can anyone help me with a git problem
Sure, but you'd be better off asking in #tools-and-devops 
I fixed it nevermind haha thank you for the tip though
That's awesome glad its getting some recognition
I want to get into the aiohttp world but I am not there yet
Quart seems like a good choice to start transitioning from flask to aiohttp
[FLASK]
Can anyone recommend me a way to compress images based on Viewport width/height or something like it and to handle which image gets rendered based on it?
@tired root resize would be good, if I can dot it based on parent's element width/height, but also compressing it would be good, maybe 75% instead of lossless
You need to explain what you want there exactly
first of all, viewport can only be queried with javascript, you could then call a route in flask to obtain the image while posting the desired size
then use PIL or so to resize the image
but usually one goes with 2-3 sizes and uses one approperiate
compression can be done with webp
that is a rather newish algo for images
PNG can also be compressed far more than people know
I use png gauntlet to compress before I upload to my web
@tired root I think that I want an app to manage 3 versions of the same image for me...Let's say a Mobile version, Tablet version and Desktop version.
So, it would generate 3 images for every image and based on the viewport it would render the appropriate image...I think that would be best for performance, because if I try to resize image as the user changes the viewport, it would overload my application
yeah, something like that is done statically
Use this for compression: https://pnggauntlet.com/
It's free
I have used GruntJS for that before, but it was a long time ago and I think I want something more "flasky"
Cool, is it any good for .jpg images?
I don't really have a choice, I have a bunch of .jpg files with pics of apartments and buildings
JPG is very lossy, while png is lossless at a comparable size
Then you can't do any further compression
only resizing
How do you handle the resizing based on the user's device?
don't do that. Decide on 3 sizes: Large, Medium and small
That is the common way to decide between devices
COmputers = Large, Medium = Tablets, Small = smartphones
Yes, but I mean, how do you decide between those 3 in the back-end/jinja
You don't. you use media queries in css
/* Must be at bottom */
@media only screen and (max-width:720px) {
.text-right {
text-align: left;
}
.sidebar-wrapper {
display: none;
}
.content-after-menu {
padding-left: 0;
}
}```
Simple example
This changes the selectors listed on any screen smaller than 720px across
there you can use something like background-image to decide on which image to load
you can also use Javascript and load the image async
I see, but I'm using img tag to render most of the images
.my-image{
background-image: url('picture512px')
}
@media only screen and (max-width:720px) {
.my-image{
background-image: url('picture256px')
}
}```
May use javascript's window.innerWidth; then
if (window.innerWidth <== 720){
document.getElementById("image") // etc
}```
I am bad with JS, but you get the gist
Gotcha
Will see how can I implement something that works for my app as it is
Need to keep it consistent, my current score is like that. But in order to keep the performance score high on all pages I need to automate the image stuff
what tool is that?
hey guys what would you use to display output of some function onto the same web page?
The answer probably involves Flask, but it depends on exactly what you want
Indeed using Flask, return <template> would load a new page with the results but I'm wanting to have it appear on the same page
The easiest solution is JavaScript
and AJAX
What you'd want to do is set up a new Flask route that returns a JSON, then send a request to that route via JavaScript using the FetchAPI.
If you're ok with the page refreshing, you can just use a form instead, and set up a POST route in your Flask @earnest oak (just a route to receive the incoming form, doesn't have to be POST)
This code is supposed to send a message to a netcat server. It does that fine but the problem is that it closes the connection on both ends after it is done executing. Can someone tell me how to get it to stop stopping the server on both ends?
import socket
import sys
import time
IPA = '' # Where you would enter the host ip
portA = '' # Where you would enter the host port
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
IP_address = str(IPA)
Port = int(portA)
server.connect((IP_address, Port))
message = "hello"
server.send(message)
sys.stdout.write("<You>")
sys.stdout.write(message)
time.sleep(5)
Whats the issue?
so I have
def calculator():
if request.method == "POST":
is calculator() a route?
and at the bottom I have
return render_template('calculator.html', entry=entry, sl=sl, tp=tp)
yes it's the home route
it's under
@app.route("/", methods=['GET','POST'])
sure
so outside of the if statement,
I have it return render_template('index.html')
so what it should do is take the entry, sl, and tp and return an output underneath there when I click "calculate" button
I'm trying to figure out how to get it to display in the same page
It does run, but there's no display
Just so I'm clear on whats happening.
You have a form, that form gets submitted as a post request to this route. Then if the route receives a post request, you extract the formfields, process them, and return a rendered template?
yes! that's what I'm trying to say
I'm almost there to getting it but certain things are throwing me off. Like in that rendered template I want returned, there's a "Calculation: <output here>" , and before the "calculate" button is pressed, I shouldn't see anything down there. But I see "Calculation: ____" before any input or button is submitted
That sounds like a jinja issue. Can you paste the relevant bit of the template?
<div>
{% if has_calculated %}
yay
{% endif %}
</div>
You should have something roughly like that
to keep the script running in an EC2 instance, what do you use? screen?
me, no
I use whatever the system's "init" thing is
I got a config file in /etc/init that says how to run it
I see
can I ask a flask question here?
after setting up a server and putting nginx on it, i thought i could just dump stuff in /var/www/html and i would be able to see that in the browser, that isn't the case though, i just have
That's usually the case--do see what the configuration for nginx says
it's usually at /etc/nginx/nginx.conf or close enough
it should have a "root" that tells you where it's serving files from
if you're on osx, that could be /usr/local/www
@native root on a ubuntu server, ok cool, my thinking was that I could just dump a directory and access it using this? I don't need anything fancy as it'll just be a dir of html reports
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
is at the top
i'm not too sure what the problem is i'm trying to solve because i don't usually use servers or web stuff, i don't care about making a site, i just want to host some report files 🤔
ok this seems similar
root /var/www/html;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
The file i can see when i go to the IP of the server is index.nginx-debian.html , how to make it so that it just gives me a dir structure?
There’s your root
or do i need to code that, i thought that dir structures were just a default
yeah - and this file is what I can see in the browser
Then that’s it
but i want to dump a directory with reports in it, and that has sub directories
but that's all I can see, i can't see the directory that I've put in this folder
Did you copy with ‘sudo’?
Try ls -al
yeh i can see it - teh dir is definitely here
If the files you want read root root
Then you didn’t adjust permissions so Nginx can read them
they do
ah ok
drwxr-xr-x 3 root root 4096 Mar 24 02:05 .
drwxr-xr-x 3 root root 4096 Mar 24 02:05 ..
drwxr-xr-x 2 root root 4096 Mar 24 01:55 reports
-rw-r--r-- 1 root root 612 Mar 24 01:42 index.nginx-debian.html
but the other file is the same
ok, so it handles the case of index.nginx-debian.html on my behalf, but won't do the rest
‘chown www-data www-data [files]’
Add a -R at the beginning to recursively apply to directories
sorry to be daft but this syntax, chown [OPTION]... [OWNER][:[GROUP]] FILE... is in the man page
so my option is recursive, my owner is www-data and my group is www-data, and the file is a directory
chown: cannot access 'www-data': No such file or directory
sudo chown -R www-data www-data reports/
it seems as though I've followed the guide
ok I needed : it seems
drwxr-xr-x 3 root root 4096 Mar 24 02:05 .
drwxr-xr-x 3 root root 4096 Mar 24 02:05 ..
drwxr-xr-x 2 www-data www-data 4096 Mar 24 01:55 reports
-rw-r--r-- 1 root root 612 Mar 24 01:42 index.nginx-debian.html
👍
still doesn't work tho, just get that index page and nothing else
ah, hey ho
👍 forgot the colon >.<
😄
it didn't work anyway, i think i'll leave it
unless there's a google tip - i'm not sure what this is called
that's what i get if i try to go to reports dir
ive run sudo systemctl restart nginx
no
Ok. So by default NGINX looks for an index.html file, and if it's not found will do as above
hrm, i thought things just showed dir structures?
like websites and stuff,. isn't that a default? Oh ok
eventually i'll need to pw protect this stuff, but just trying to get an idea of it atm
autoindex on is the config value, and you can provide it in a block...
Here's an example:
god, not knowing the right words for anything makes googling way slower 😅
thanks
ok lol i give up tonight, i';ll look tomorrow
thanks bast 👍
good luck >.<
Trying to have my web app to redirected to the home page after the form is submitted but it just gives the form's query in the address bar. For example /form?Name=input&Location=input
def home():
return render_template("index.html")
@app.route("/form", methods=["POST", "GET"])
def form():
if request.method == "GET":
return render_template("form.html")
else:
return redirect(url_for("home"))```
form.html
```<form method="POST" action="/form">
<input type="text" name="Name">
<input type="text" name="Location">
<input type="submit" value="submit">
</form>```
they do. I did change form action to "/" to see what happens and got "Method Not Allowed
The method is not allowed for the requested URL."
where is "request" defined?
from where?
ah
seems to work for me 😐
I'm running this single file
from flask import Flask, request, redirect, url_for
app = Flask(__name__)
@app.route("/")
def home():
return "Hey I'm the home page"
@app.route("/form", methods=["POST", "GET"])
def form():
if request.method == "GET":
return """
<form method="POST" action="/form">
<input type="text" name="Name">
<input type="text" name="Location">
<input type="submit" value="submit">
</form>"""
else:
return redirect(url_for("home"))
I wonder why it won't work from an html file?
🤷
How can I predefine the meta data for iOS user? I tried the given code line from the official Apple site but when I change that meta website name to something, and then want to add my website to my homescreen the name is App and not the name which I chose and even when I set the meta data for the launch screen to a picture that won’t appear when I open my website from the homescreen shortcut
This can't be normal... ran up a $20 charge in like two days getting this web app set up on AWS
Why route 53 gotta keep charging me though
If you are trying to return the page from a html, what I did was use return render_template(‘file.html’) and have file.html in a file in the same directory called templates, and it works
@wind merlin I usually use the apple prefix in all my rels
And it works
eg
<link rel='apple-touch-icon" href="myicon.png">
@rustic pebble yes the link tags are working but these one wont work
<meta name="apple-mobile-web-app-title" content="4-Shisha KombiListe"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black">
When i try to create a homescreen shortcut to the website the given Name is App and the safari menu is still active
And this one wont work
<link rel="apple-touch-startup-image" href="{{ url_for('static', filename='launch.gif') }}">
Url_for is installed because i used it for all the icons and launch.gif is existing
Heya! I'm currently working on a Django app, and I'm having an issue with templating.
E.g. take this example code:
{% for charge in charges %}
<tr>
{% for field in fields %}
<td>{{charge.field}}</td>
{% endfor %}
</tr>
{% endfor %}
I have an array of objects called "charges", and an array of fields called "fields".
Let's say that a charge is a dictionary {"a":1, "b":2, "c":3, "d":4}
Given the array of fields a, b I want to only parse charge["a"] and charge["b"]
but right now it's trying to parse charge["field"]
I'm guessing that I need to do some kind of double-templating or template-escaping, but I'm not sure how to proceed. Any ideas?
(edited because I was showing a wrong example)
For now, I've just created a Charge class which will return an array of it's own values, given a list of fields, and handle this logic in a proper python function instead of in the template. Still curious if it could be done with templates
You’re reaccessing charge.field in the inner loop
You should just access field, presumably
Ah, but field is just a or b, what I want is charge['a']
What I have now, instead, is:
{% for charge in charges %}
<tr>
{% for bar in charge.foo %}
<td>{{ bar }}</td>
{% endfor %}
</tr>
{% endfor %}
which is to say, that I solved it by using a class with a function 'foo', which returns an array of the values I wanted.
Newbie question here (google answers are vague and are from 7 years ago) can python replace javascript for front-end application?
Short answer : nope
Long answer : it can, but the tech isn't enough mature for now to be used in production
that's unfortunate
Yep
okay, thanks for the answer.
we are well on our way to having things replacing javascript in frontend though and actually some things are already making it possible so the future is bright for that question although javascript will probably never be fully replaced ever in the web
Why do you want to replace javascript?
we are well on our way to having things replacing javascript in frontend though and actually some things are already making it possible so the future is bright for that question although javascript will probably never be fully replaced ever in the web
@severe folio check wasm: Webassembly, it is based on js, but it is completely different. There are some wrappers that are being developed like Blazor
Blazor is a feature of ASP.NET for building interactive web UIs using C# instead of JavaScript. It's real .NET running in the browser on WebAssembly.
thats what i mean ive used blazor quite a bit but for python we are not quite there
I dont think python will ever get there
only if someone builds a wrapper for wasm
But I believe the complexities are many
i think it can get there and someone will eventually make something now how much it will be used i can not comment on
That gave me an idea
We're pretty damn far from replacing JS on the frontend
yeah but things are happening and over time it could be a reality that alot of sites never wrote a line of js BUT again i think 100% javascript is always gonna be used by more people then anything else on the web
Modern JS isn't even particularly bad - the pain comes in no small part because you need to support old browsers; and we're probably a long way away from being able to use WASM to replace that
i agree
Hi, can someone offer advice on lowering DNS query serving costs? I'm just running a simple web calculator on an EC2 instance and the Route 53 DNS querying is costing me like $6 /day
can someone help me about django ? tks
!aks
*args and **kwargs
These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.
Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.
Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.
Use cases
• Decorators (see !tags decorators)
• Inheritance (overriding methods)
• Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
• Flexibility (writing functions that behave like dict() or print())
See !tags positional-keyword for information about positional and keyword arguments
!ask whoops
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.
• Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
• 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.
• Be patient while we're helping you.
You can find a much more detailed explanation on our website.
Hi! I'm working on a Flask project and trying to add "projects" section where I want to put PDFs of my papers, code snippets, guide through math/coding problem. What's the best practice way to organize my project? So far I have created a blueprint "projects". Should I store files on Google Drive/Github and somehow embed them, should I create a .db, etc? Thanks
Is Django for the frontend or backend? i don't understand
Django is a full stack framework, which means it handles both backend and front end (in the form of templates). Its not a front end framework in the same way React/Vue is though - it only renders static HTML, so I see it more as a backend framework
it's clear now haha, ty
No Flask people in here?
Yeah I would probably go the embedded github url route
if pdfs are long and you are gonna insert them all the time, it might be easier to use gdrive
but it's more work for connecting your api with gdrive
hey saki
