#web-development
2 messages Β· Page 39 of 1
hey guys can someone that's familiar with hosting Selenium on Heroku clarify some things for me please please
So im tryna do this in my site https://hastebin.com/umalinisut.xml but i get a glich when scrolling slowly.
in wtforms with a selectmultiplefield and want to make sure the user is selecting at least n options from the available choices. is that something that would require a custom validator?
Can you elaborate?
a selectmultiplefield like this. I'd like to make sure at least 2 options are selected
Can you show what you've done in terms of code?
class PairForm(FlaskForm):
origin = SelectField(u'Origin', choices=symbols,coerce=str)
destination = SelectField(u'Destination', choices=symbols, coerce=str)
languages = SelectMultipleField(u'Languages', choices=languages, coerce=str )
distance = FloatField('Distance')
class PairsForm(FlaskForm):
pairs = FieldList(FormField(PairForm), min_entries=len(config_file))
submit = SubmitField('Save')
I think you are gonna have to write custom validator
This is a design question, I'm not 100 sure about this text box, what do you guys say
hi guys, i'm all new to python, i am a beginner in c#, know some html/css etc. i want to make a small website based on python. I installed the Python add-ins to VisualStudio, now i see that almost all Python Web Projects use Bootstrap, is there a "beginner friendly" web framework? I can choose between these frameworks: Web Project (only Python), Django, Flask, Bottle & Flask/Jade. Could you help me decide? Thanks in advance! π
Get into Flask or Django, they are mostly used and have a bunch of tutorials online
also I recommend using some kind of a text editor since you will mostly be running instances of local servers
as for frontend you can do fine with just bootstrap, but I'd recommend getting into Javascript and a framework if you want to do web development
Thanks for the answer @native tide. I just wanna get this project up and running for now, but thanks, if i really want to get into web-dev, i'll look into js more! π
id say dont worry much about the frontend, concentrate on the backend first, html and css should be satisfactory while learning backend @round kraken
I have a different opinion, I am currently working on a project, and because I dont know enough css and html my front-end development is very slow, cause I cant get things to work properly
@round kraken flask is very beginner friendly and corey schafer has very good tutorial series
And i see you are another fellow croatian in this server :))
@vagrant adder not croatian, but fellow european π how did you get to that conclusion? ^^
@marsh canyon Will do, thanks!
damn.. i've always created websites by hand (that's how we learned html/css), flask makes everything 100% more intuitive, it makes html fun again π so glad i found this.
guys, I was using a database for testing, while developing a web application with flask and sql-alchemy, now i need to replace that database with another database (always sql), can you tell me an online tutorial for how to replace a database with another?
So you are changing from let's say, mysql to postgres?
no i'm changing from sqlite to mysql
but now I have to use a database that has given me a friend of mine who works with me and i don't know where to put this .sql file
Just put it in the same folder as your sqlite db
And delete sqlite and change uri in the config
yes.. but a little complicated, I created it at the command line with flask, and I don't find it lol
this is the config
for the old database
sqlite
ah cool! it found it, in the project's main folder
Can i see that .sql file you got?
yes, I send it to you in dm?
mm yes i think
And db.create_all() creates the same exact thing
You said you want to migrate to mysql
mm so do I only need to take the names of the tables? shouldn't I put the file anywhere?
Proper way to do that is to setup a mysql server, create a user and database manually
The file you got isn't really needed
ah ok but I can also stay in sqlite, but i have to make sure that my web app makes changes to its database when it will be on its vps
What vps you are using
Hi all. I have a problem with creating nested objects in DRF. I have described it in #help-coconut . Should I post it again here?
I still don't know very well but it is based on linux, but it is already in the tutorial that I am following the guide to migrate on linux, but one thing:
I mean, what vps provider are you using
Heroku, digital ocean, linode, pythonanywhere
ah sorry, it's a private server
but if I change the names of the attributes that I am using in the web app with those of the sql database, when the web app is on the vps connected to my friend's database, should it work?
and the code of my "models.py" will no longer be needed?
like this:
the server is not from a provider, another friend owns it
at his home
Yes you would still need models
So sqlalchemy knows what the hell to query under the hood
Every time after you change attributes in models.py you need to db.drop_all() and db.create_all()
So the point of sqlalchemy is to remove raw sql in any shape or form
That's what ORMs usually do
mmm do I need to make my models the same as my friend's database?
So the thing is, when you enter the database uri in your SQLALCHEMY_DATABASE_URI and do drop_all() snd create_all(), you are effectively changing database definition to match it to your models
There isn't any need and point in changing anything except SQLALCHEMY_DATABASE_URI in config
ah, perfect, but one thing: I did not understand how the ORM knows that my password_hash in my model corresponds to acc_password of the database connected later
for example
or 'username' to 'acc_username'
So, in your file your friend defined some tables blah blah
Once you do.db.drop_all();db.create_all() will override those with ones defined in your models
Don't worry about the file, it isn't relevant
This is the file i use for doing that the fast way
ahh I understand now, thank you very much for the patience you have had and for helping me
i'll try with this
π
I have a 404 page, and I want to modify the contents of the html (to include {% extent ... %} and {% include %} ) but only if a user is logged in / authenticated.
the 404 page is an errorhandler , and I am currently using Flask
is there a way to do that?
yes there is an errorhandler in flask, mind explaining what you want in bit more detail?
the error page is basically an a small <div> with text in the center of a page
I want to load the navbar.html and layout.html only if the user is logged in
i usually load these htmls into any other using {% extend layout.html %} and {% include navbar.html%}
I'm gonna try to finish a "my first django app" thing today. The file structure is so ugly. I wish therere didnt hvae to be a project with folder of the same name in it and then an app in that. I dont see why its so much folders.
it's like... at least two inwards paths into what ive created so far
I can look at the absolute path
and see the same folder name inside of each other
that is never sensibler lol
maybe it will make sense as i keep doing it
But I wouldnt be surprised if i alwasy thinks this file strucuture is a mess
the whole django is a structured mess
I can see very early on but thats ok. So am i
The guy I have teaching me right nos is not the guy I need.
He doesnt explain why he does things often enough.
But it happens
is render() a django thing only?
does the Flask WTForms StringField() not allow special inputs? when I try to search with "the" or "for" I get the value of form.search.data = None instead of form.search.data = for
this seems to happen for anything shorter than 4 characters
so form.search.data is None if user enters something than 4 characters?
something less than 4 yes
really?
yeah
try setting it to min=0
i'm out
π
I'm having troble figuring out why my bootstrap and css are getting 404s in local host when I view the source and click them it appears.
But there are things different about this
this templating language and loading static
and obviously with this many folders everywhre
you're going to struggle with this
So why its that way i dont know
weird
i'm sorry, i didn't understand any of that well. what's the issue and what are you trying?
So I'm using Django for the first time and there is this templating language of like
<link rel="stylesheet" href="{% static './todo/bs/css/flatly.min.css' %}" />
<link rel="stylesheet" href="{% static './todo/styles.css' %}" />
I dont really know if that is the source of the problem. Im literally just copying an example first projerct but something isngt right and its not getting the paths right to these css files.
it might have to do with running it localhost
it's called Jinja yes, but i've never seen css used like that. i only have experience with flask and it's a pretty straightforward bootstrap implementation, sorry
Its okay. YEah, Im familiar with that Jinja exists but not enough to know how to get it to work when it doesnt.
Its weird
Because if I view source on my unstyled html
and click the link to the stylesheets
they go to where they would go to you would think
in otherwords they load the file in the browser
Okay so this bloody wild
view-source:http://127.0.0.1:8000/bs/css/flatly.min.css --- this will load the text for the file
http://127.0.0.1:8000/bs/css/flatly.min.css this will 404
any ideas?
It seems to definitely hav something to do with a configuration i have somewhere that im new to
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('todo.urls'))
the weird thing here though
is it calls that file project.urls
bit its not
its urls.py inside of project
project is a dir
is that wrong?
Maybe I need a better instructor...
Maybe I should do flask lol
wait there is no way that / after admin can be right
is it?
regarless of what it is
the problem is 100% this instructor who just shows us what he is doing and not why he is doing it or what it affects
next
@native tide I don't know if Jinja in django works exactly the same as Jinja2 in Flask, but when I put in the css using jinja2 i did it this way
<link rel="stylesheet" href="{{ url_for('static', filename='styles/base.css') }}">
but i dont know if the jinja for django is a different version or has different syntax or not
I definitely remember when I looked at Flask... that is how I did it as well I think because that looks familiar from when I looked at it. But... yeah, the problem is that Im copying an example of a guy who is not bothering to explain it.
So I have to try another example
like its my first one
i have to assume it will work
π
I could be wrong about this
But I believe that {{ }} in jinja means
get this value
and {% %} means do this logic
am i wrong?
yes thats correct
well the logic is correctly sending what I think would be the url
then maybe jinja in django is different than that of Flask π
should be the exact same. unless they're using different versions of jinja, jinja is jinja
its def more or less the same jinja. jinja is just powerful and can do a lot of things in different ways
GET /bs/js/bootstrap.min.js
This was in my console
if thats all its trying to get obviously its a 404
But like...
Its just weird. And I cant really make sense of it because this is my first example of this and i dont know what anything means. But im gonna do thorough reading i guess and just chill today im too tired to start a new thing unfortunately
I wish that when you got into more advanced topics that there were still people writing all these books to teach you lol
hmm, well I think that if you learn the basics correctly, you should be able to handle the more difficult stuff cause you should now understand what your doing and what you want
the problem is at the beginning when you dont know what your doing and you dont know what your allowed to and not allowed to do
yeah, I am capable of figuring it out. But.. I will say
That this framework thing is way different than anything else in Python I have done
So it is a new thing
Buit ill get it
TBH
one of my worst flaws is that I dont allow myself to be aware when i am too tired to be trying to do something new still. Like Ill go from rested and productive to...
"Oh right... I bett my mind will work better later."
tomorrow
fucntion changeBG {
var bodyBG = document.getElementsByTagName('body');
return bodyBG.style.background = 'white';
};```
anything wrong with this JS code?
i am a javascript beginner.
im trying to change the background when clicked on an element
this one
<header>
<i class="fas fa-adjust" onclick="changeBG"></i>
</header>```
i need help
i don't know why it's not working
fucntion -> function,
function changeBG -> function changeBG()
function changeBG() -> var changeBG = function()
onclick="changeBG" -> onclick="changeBG()"
ok , thanks β€οΈ
(actually, the web doesn't need html, or css, or js, or python either)
php isn't bad. It actually has better performances than python in most use-cases. Php "developers" on the other hand...
anyone using ariadne graphql?, how do you guys write unit tests for resolvers when using ariadne graphql with django?
I am using graphene and i'm using unittest
Ariadne seems like a mess
It looks like it is a slow development process to do something
@vagrant adder graphene does support unittest right?
Yes it does
@stiff totem I know it's not your question, but if you have time, check out the tartiflette graphql lib, it's really awesome: https://tartiflette.io/
@teal comet nice I'll check it out
Hey guys, actually I have two questions regarding single topic:
I have following application: Scrapy(scheduled scraping + data processing) + Django(simple visualization of scraped data), the questions are:
- how would you separate those architectural components? Former developer simply put all of it (django+scrapy+mysql) on single 5$ server and runs scraping via cron - it was understandable in the beginning(low cost). But it's not ok from scalability perspective of course. I thought about adding Celery beat and celery worker, but it can be an overkill for simple scheduled scraping. I think that also scraping + data processing on web server is also not acceptable(maybe Im wrong). Do you have some ideas?
- Which hosting for such application would you recommend? It's docker based and low cost is important factor here
Thanks
@lucid night how big is your scale really?
if you're really handling massive data and think you won't be able to handle everything on a single server, consider using kubernetes
you will have to put each part of these components into different docker containers, which you will be able to launch whenever you want
it has a feature called cronjobs, allowing to schedule some regular tasks: https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/
most major hosts (google cloud, aws, digital ocean, linode...) offer managed kubernetes nowadays
however, if you just struggle with a 5$ DO server, maybe just consider buying a larger server at the start before jumping to distributed architecture, kubernetes and all that
Thank you @teal comet for suggestion.
How would you handle such split(scrapy separated from Django models)?
In fact, going for bigger server could be ok but it was POC from former developer, soon traffic can grow to ~1000users per day and requirement was to prepare for that π
There's no single answer to that, especially since I don't really know what you're doing
I would two docker containers
- one running scrappy, controlled by a cronjob
- one running django, controlled by a deployment
both would probably communicate by sharing a common database (either managed or in a third container)
also thoursands of users per day can be easily handled by running one or two large server, unless you're doing some extremely CPU intensive tasks idk
That's good idea, my question was not precise - would you redefine DB models in scrapy container - or is there any other way to reuse it?
both work actually, you can either redefine models in the scrapy container or share a common codebase between the two containers
having multiple repositories will bring you more flexibility and might be easier for large orgs
otoh being in a monorepo makes it easier to avoid code duplication and might allow you to get a faster time to market if you're a small org
Thank you Seto
no problem π
hi
anyone knows how to customize the @login_required flash error message in flask?
the standard is Please log in to access this page.
can i see your route?
thanks! however I didn't understand where to put it, this is the index route:
@app.route('/dashboard')
@login_required
def index():
login_manager.login_message = u"YoU aRe nOt lOOggEd iN :3"
user = {'username':'kocis'}
news = [
{
'author': {'username':'John'},
'body': 'Lorem ipsum dolor sit amet, consectetur'
},
{
'author' : {'username':'Luca'},
'body' : 'Risus ultricies tristique nulla aliquet enim tortor'
}
]
return render_template('index.html', news=news)```
I tried to put it on top, but it doesn't work
Google says
from flask import Flask
from flask_login import LoginManager
app = Flask(__name__)
login_manager = LoginManager(app)
login_manager.login_message = "whatever"
Now that's weird
wait
I've never used flask so I can't help much more, ask me anything about django though π
why am I doing wrong with my code https://dpaste.org/tDNV that I cannot structure like this to retrieve id , value in my json https://dpaste.org/tt5g?
What is this UI UX thing i see everywhere
Design stuff
Is it handy?
Should a webdeveloper learn it?
should I learn plumbing?
the more you know, the more you can get paid.
but ... you might not be good at it
pretty sure I wouldn't be good at plumbing
Having a bit of trouble figuring out what exactly I'm looking for here. I've created a custom website with Flask, however, it's not exactly the ideal medium, as it's basically a static site that rarely changes. I was mostly using Flask to interface with the jinja2 templating engine, because I have a lot of individual pages that I'd rather not create by hand. I'm looking for a sort of program that can be executed once and it will generate a static site based off of templates and given data. I researched static site generators and they don't seem to be what I'm looking for - as they seem to be based around blogs, but this site isn't a blog. Static site generators also seemed to be geared towards creating a site off of a pre-existing theme. Rather than that, I'm looking for a program that is able to generate hundreds of pages off of an input so that I don't have to do it by hand, but also, take completely custom HTML and CSS. Does anyone have any advice?
Not exactly, if I'm understanding your correctly. Rather looking for something that will generate the entire site off of info I provide.
Oof, think that isn't possible
There are flask_cookiecutter and such but that is just a basic template for a project structure
I don't see why you couldn't implement something like this yourself
jinja2 itself is very easy to hook into, you simply create an environment, load your templates, and begin rendering and saving to files as you go. I've done hookups to various data services for this, and it works quite well for static sites like you describe
ultimately, the data format is almost always custom, and so you'll have to do the translation of data -> template variables yourself. If the data also encodes what pages to generate, really you should probably write a short script that simply formats the data into template variables and calls into jinjas render, then saves it to a file
Something of the format:
def generate_for_data(dest, data):
return template.render(etc)
for page in pages_to_generate:
with open(out, "w") as f:
f.write(generate_for_data(page, data[page]))
works well enough. Jinja is fast enough that unless you've got some massive sites I would expect fraction-of-a-second render times, so there's really no reason to cache
I created a boilerplate generator, but that's only foundation for the app
You can take a look if that's what you want
I doubt it
@cinder hatch Look into static site generators. Gatsby, jekyll, hugo etc...
I researched static site generators and they don't seem to be what I'm looking for - as they seem to be based around blogs, but this site isn't a blog. Static site generators also seemed to be geared towards creating a site off of a pre-existing theme. Rather than that, I'm looking for a program that is able to generate hundreds of pages off of an input so that I don't have to do it by hand, but also, take completely custom HTML and CSS.
Ah, didn't see, sorry
I've used nuxtjs for a lot of things, not only blogs, and I wasn't using a theme
can we cache the information like google map content using service workers ?
Can anyone answer my question here?
quart
Considering that I have this websocket thingy
@app.websocket('/ws')
async def ws():
pass
How can I restrict access so only people with a certain session values can connect?
How, with flask, can I have both: @app.route("/project/<name>", methods=['POST', 'GET']) and @app.route("/project/<name>/delete", methods=['POST', 'GET']) without getting:
AssertionError: View function mapping is overwriting an existing endpoint function: project
It was my functions, not the routes ;-;
const mongoClient = require("mongodb").MongoClient;
const url = "url";
const dbname = "name"
class Users {
constructor() {
};
static insertUser(payload) {
mongoClient.connect(url, {useUnifiedTopology: true}, function(error, db) {
if (error) throw error;
var dbo = db.db(dbname);
dbo.collection("Users").insertOne(payload, function(err, result) {
if (err) throw err;
db.close();
});
});
};
};
console.log(Users.insertUser({_id: "Test", email: "test@test.com", password: "tasdqwefsfdgv"}));
How can I return result so Its logged out? Also let me know if Im doing any bad practices, ive only been learning node for like a week now hue
Not sure you're gonna find lots of people who can help you with nodejs here π¦ I barely touched it and can't help, sorry
Its fine, thanks anyways
I want to build a simple app, nothing too complex. Will Django with rest-framework (for REST backend) and Angular be a workable combination?
Sure. Django may be overkill if your app is simple, but it'll work
I was using sanic, but TBH I donβt want to deal with all the stuff like authentication and SQL injection...so...
Simple REST frameworks can also be done easily with PHP. DOn't dismiss it too fast. But all depends on what you are doing.
Do i need to know JS to make a collapse navbar?
Theyβre not too hard @marsh canyon try have a look on w3 school for it
Quite easy to follow on there
ohk
has anyone worked with Eel yet ? Can someone compare it to building electron apps with a Python Backend ?
Looks interesting, thx for the link
well, I donβt know PHP, and I do know Python, so that alone is enough, I think
from flask_login import UserMixin
from flask_sqlalchemy import SQLAlchemy
@login.user_loader
def load_user(id):
return accounts.query.get(int(acc_id))
accounts = db.Table('accounts', db.metadata, autoload=True, autoload_with=db.engine)
characters = db.Table('characters', db.metadata, autoload=True, autoload_with=db.engine)```
guys i've this issue:
AttributeError: 'Table' object has no attribute 'query'
Because you can't query a table in sqlalchemy
You can query models however
db.Table is used for association tables for many-many relationships and other tables used for connecting
wot
i am confused
you need to create account table that is inheriting from db.Model
hey! does any one ever use the django-scheduler from : https://djangopackages.org/grids/g/calendar/ ?
Anything that has to do with scheduling and calendars.
I'm trying to implement a calendar on my website and i installed this package but not sure how to use the calendar example
the readme at the github repo is very poor and the example provided is working with JS files
@vagrant adder i did this:
and
^this instead of user = accounts.query....
and it works
Does anyone have any good tutorial for communication between javascript and python? I'm running a flask app and want javascript to fetch some info backend from a python function
@stiff frigate The only way to achieve this is using websockets. So google for python websockets and you are good to go: https://websockets.readthedocs.io/en/stable/intro.html
i cant find a button
<button class="jssubmit btn color sf" type="button">```
i tried find_element_by_class_name
and find_element_by_css_selector
both dont work
how did you search for it? IN python or JS?
never used that, sorry.
Hello all, could I have help as to why this doesn't work?
<!doctype html>
<html>
<title>Account System</title>
<script>
var validateCredentialsValid=null;
function validateCredentials(validateCredentialsUsername,validateCredentialsPassword){
if validateCredentialsUsername=="correctUsername"{
if validateCredentialsPassword=="correctPassword"{
alert("Welcome.")
}
}
}
function login(){
inputUsername=prompt("Username")
inputPassword=prompt("Password")
return inputUsername,inputPassword
}
</script>
<head>
</head>
<body>
<h3>Account</h3>
<button onclick=login()>Login</button>
</body>
</html>```
Is this a joke?
π
please read up on how these things work, before you make something like that
I know you are a beginner and I am struggling not being dismissive here, but seriously, please read a book or a tutorial or something.
I suggest starting with flask, making simple web pages with templates, then logins
and learn about why javascript is unsafe and why credentials need to be validated by a server
in short: Javascript is something the user can change and block at any time
I don't plan on using this for a large database, and do you know why it doesn't work, though?
first thing I see is that login() is not within quotes
onClick="login()"
Also, validateCredentialsUsername is never set
Same as validateCredentialsPassword
Hmm
You don't really call that function anywhere
it would need to be something like javascript function login(){ inputUsername=prompt("Username") inputPassword=prompt("Password") validateCredentials(inputUsername,inputPassword) }
Yeah, I was trying to figure out why the login function didn't work before I continued
So to invoke a function you need to put it in quotes, correct?
invoke/call
what does "prompt" do
prompt creates a dialog box on the window
it is a global variable, coming from the window object
also, you cannot return more than one value in JS from a function
return inputUsername,inputPassword
that line therefore is nonsensical
and then, even if you had login() in quotes, it would still be wrong
onClick="login()" will simply execute login on page load and so clicking the button will do nothing
you would want onclick="login" (no parens) or better yet, use .addEventListener
I also see that your if statements don't have parentheses. In JS, if, while, and for headers need parentheses
if validateCredentialsUsername=="correctUsername"{
you should instead do
if (validateCredentialsUsername == "correctUsername") {
validateCredentials is also never called. Therefore, the alert will never pop up
instead of returning from login, you may want to call validateCredentials
function login(){
inputUsername=prompt("Username")
inputPassword=prompt("Password")
validateCredentials(inputUsername, inputPassword)
}
@dapper sage
You also may find better help in servers specifically for JS as the people here are less likely to know much about it
any1 else experiencing heroku logs offline?
oh, I thought it was just me
it says it isn't available. Had no idea why
@spare canyon
if u visit the help center, u'll see every1 having this problem, so nw
Heroku Status provides the current status and incident history report for the Heroku platform.
Does anyone know how to scrape Google maps
Isn't that against the TOS ? You may wanna check their api instead https://developers.google.com/maps/documentation
@bleak bobcat I wanna get like the swimming pools that are present in the NYC area
{"detail":"CSRF Failed: CSRF token missing or incorrect."} I removed middleware, use csrf_exempt, removed and clear cached , irony is that api works perfectly with curl but not with fetch() API in django,django-restframework
Is there a way to display the local time date in a django template? I have tried adding the 'localtime' filter , however the dates are still displayed in UTC format. The only way I could make it work is to set the time zone in the settings file to the desired one, but I want an automatic conversion to the localtime whenever the page is rendered
Just to give some context - I'm building a journaling app and I want the date automatically added after each entry. Any help is appreciated!
guys when i log in into my testing web site
it returns this
but it doesn't tells me the errors in terminal
Turn on the debug mode
how can i do it? I did FLASK_DEBUG = 1 but it stays off
type in the terminal 'export FLASK_DEBUG=1' before running the server
ok thanks
I did set instead of export, as for windows it is equivalent to set, but debugging remains off
for me FLASK_DEBUG =1 didn't work
but this did
set FLASK_ENV=development
@cloud path
Could anyone help me figure out why my flask app is inexplicably beginning to return my index route as 'localhost:5000/index/' instead of 'localhost:5000/index'?
@main.route('/')
@main.route('/index')
def index():
return render_template(
'index.html',
title='Windows, Doors and More',
header=session.get('header')
)
the addition of the '/' to the end of the url is causing a 400 error when I click an a tag with an href pointing to my homepage
<a href="{{ url_for('main.index') }}">
<img class="logo-img" src="{{ url_for('static', filename='images/logo.svg') }}" alt="Aluminum Associates">
</a>
an example of an href that gives me the error
@tranquil robin it works thanks
ur welcome
had given me a debug, now the site has an error but it does not give me the debugging and the debugging is still off :/ any other suggestions?
ok i've fixed it
I had to write it in the .flaskenv file as I use that and it overwrote it on startup
@cloud path if you have a
if __name__ == '__main__':
app.run()
you can put the debug = true between the run brackets like so:
if __name__ == '__main__':
app.run(debug=True)
In flask, "/index" and "/index/" is not the same thing @pliant hound
Yeah, I just cannot for the life of me find what was causing the route to return β/index/β
It seems to have resolved itself after a reboot, but yeah. Wacky bug
Anyone around here familiar with tornado?
Heyo
I'm trying to add a wave to my site from getwaves.io.
I want to make the whitespace the color below it.
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"><path fill="#7289DA" fill-opacity="1" d="M0,160L48,138.7C96,117,192,75,288,101.3C384,128,480,224,576,245.3C672,267,768,213,864,176C960,139,1056,117,1152,128C1248,139,1344,181,1392,202.7L1440,224L1440,0L1392,0C1344,0,1248,0,1152,0C1056,0,960,0,864,0C768,0,672,0,576,0C480,0,384,0,288,0C192,0,96,0,48,0L0,0Z"></path>
</svg>
Thats the wave's svg ^
Any ideas?
<rect width="100%" height="100%" fill="#7289DA"/> could try adding that as the first child
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"><rect width="100%" height="100%" fill="#7289DA"/><path fill="#7289DA" fill-opacity="1" d="M0,160L48,138.7C96,117,192,75,288,101.3C384,128,480,224,576,245.3C672,267,768,213,864,176C960,139,1056,117,1152,128C1248,139,1344,181,1392,202.7L1440,224L1440,0L1392,0C1344,0,1248,0,1152,0C1056,0,960,0,864,0C768,0,672,0,576,0C480,0,384,0,288,0C192,0,96,0,48,0L0,0Z"></path>
</svg>
so that
Alright, I'll try it out
Nope.
The wave disappeared
Fixed
Added background-color
What am I doing wrong
class UpdateSkillEdit(View):
def get(self, request):
id1 = request.GET.get('id', None)
skill1 = request.GET.get('skill', None)
fromlevel1 = request.GET.get('fromlevel', None)
tolevel1 = request.GET.get('tolevel', None)
price1 = request.GET.get('price', None)
obj = Skilling.objects.get(id=id1)
obj.skill = skill1
obj.fromlevel = fromlevel1
obj.tolevel = tolevel1
obj.price = price1
obj.save()
skills = {'id':obj.id,'skill':obj.skill, 'fromlevel':obj.fromlevel, 'tolevel':obj.tolevel, 'price':obj.price}
data = {
'skills': skills
}
return JsonResponse(data)
skilledit.html
<table id="skillTable" class="table table-striped">
<tr>
<th>Skill</th>
<th>From</th>
<th>To</th>
<th>Price</th>
<th colspan="3">Buttons</th>
</tr>
{% for skill in skills %}
<!-- Potentially part 3 of the issue -->
<tr id="skill-{{skill.id}}">
<td class="skillSkill skillData" name="skill">{{skill.skill}}</td>
<td class="skillFromlevel skillData" name="fromlevel">{{skill.fromlevel}}</td>
<td class="skillTolevel skillData" name="tolevel">{{skill.tolevel}}</td>
<td class="skillPrice skillData" name="price">{{skill.price}}</td>
<td style="text-align: center;">
<button class="btn btn-success form-control" onClick="editSkill({{skill.id}})" data-toggle="modal" data-target="#myModal")>EDIT</button>
</td>
<td style="text-align: center;">
<button class="btn btn-danger form-control" onClick="deleteSkill('{{skill.id}}')">DELETE</button>
</td>
</tr>
{% endfor %}
</table>```
skilledit.html
<script>
$("form#updateSkill").submit(function() {
var idInput = $('input[name="formId"]').val().trim();
var skillInput = $('input[name="formSkill"]').val().trim();
var fromlevelInput = $('input[name="formFromlevel"]').val().trim();
var tolevelInput = $('input[name="formTolevel"]').val().trim();
var priceInput = $('input[name="formPrice"]').val().trim();
if (skillInput && fromlevelInput && tolevelInput && priceInput) {
// Create Ajax Call
$.ajax({
//potentially part 2 of the issue
url: '{% url "skill_ajax_update" %}',
data: {
'id': idInput,
'skill': skillInput,
'fromlevel': fromlevelInput,
'tolevel': tolevelInput,
'price': priceInput,
},
dataType: 'json',
success: function (data) {
if (data.skills) {
updateToSkillTable(data.skills);
}
}
});
} else {
alert("All fields must have a valid value.");
}
$('form#updateSkill').trigger("reset");
$('#myModal').modal('hide');
return false;
});```
function updateToSkillTable(skill){
$("#skillTable #skill-" + skill.id).children(".skillData").each(function() {
var attr = $(this).attr("skill");
if (attr == "skill") {
$(this).text(skill.skill);
} else if (attr == "fromlevel") {
$(this).text(skill.fromlevel);
} else if (attr == "tolevel") {
$(this).text(skill.tolevel);
} else {
$(this).text(skill.price);
}
});
}```
</script>
I believe it is the "skillData" within the table. but I just have no idea what to change. everything I console.log gives me all 4 columns in the row.
Hello, how do I get an object that was made by me ? For example, it's a website and I'm on my own account, so I've made a form and I want to retrieve it back in another form ( editable form )
Django
could anyone show me how to create a graph from json file?
Anyone with FASTAPI Knowledge
I want to get json body in a post request which is not defined before
so whatever the user sends in json I wanna print it somewhere
Scanned the documentation all the examples contained pre-defined json body but mine is not pre-defined
???
is there a request object like in flask?
in flask you can request.body and it returns json body
guys
if i log in into my website, it says this:
but I logged in, and with an existing account in the database
this is the code:
def login():
if current_user.is_authenticated:
return redirect (url_for('index'))
form = LoginForm()
if form.validate_on_submit():
user = db.session.query(accounts).filter_by(acc_username=form.username.data, acc_password=form.password.data).first()
if user is None:
flash('Username o password errati')
return redirect(url_for('login'))
login_user(user, remember=form.remember_me.data)
next_page = request.args.get('next')
if not next_page or url_parse(next_page).netloc !='':
next_page = url_for('index')
return redirect(next_page)
return redirect(url_for('index'))
return render_template('login.html', title='Login', form=form)```
this is models.py:
class accounts(UserMixin, Base):
__tablename__ = "accounts"
def __repr__(self):
return "User {}".format(self.acc_username)
Base.prepare(db.engine, reflect=True)
characters = Base.classes.characters
@login.user_loader
def load_user(acc_id):
return db.session.query(accounts).get(acc_id)```
i didn't use Flask a lot, but from my knowledge, you need to define the class properties under the __tablename__
so something like this.....
class Flight(db.Model):
__tablename__ = "flights"
id = db.Column(db.Integer, primary_key=True)
origin = db.Column(db.String, nullable=False)
destination = db.Column(db.String, nullable=False)
duration = db.Column(db.Integer, nullable=False)
yes I know, but I used the auto_map function that defines them automatically in case the database already exists, as in my case
I have already tried in the flask shell if it can both create users, and show them to me, and it works correctly
aah ok
thanks anyway!
π
hey guys does anyone know how to fix scrapy redirect 302 error . I am scraping a website it was working fine but now it has started to show redirection error
What do I wanna do:
I wanna sort out those appointment times, that have already been taken and display only not unique times, so people don't have to trial and error all set appointments before finding one what isn't taken
<form method="POST">
{% csrf_token %}
{{ form }}
<button type="submit">Set appointment</button>
</form>
# Views.py
class AppointmentView(CreateView):
# models = Appointment
template_name = 'appointment.html'
success_url = '/thanks/'
models = Appointment
fields = ['time', 'firstname', 'lastname', 'email', 'phone', 'message']
def form_valid(self, form):
form.instance.created_by = self.request.user
return super().form_valid(form)
def get_queryset(self):
return Appointment.objects.order_by('time').distinct()```
```py
# Models.py
class Time(models.Model):
date = models.DateField()
time = models.TimeField()
class Appointment(models.Model):
time = models.ForeignKey(Time, unique=True, on_delete=models.CASCADE)
firstname = models.CharField(max_length=150)
lastname = models.CharField(max_length=150)
email = models.EmailField()
phone = models.IntegerField()
message = models.TextField()```
```py
# urls.py
path('appointment/', AppointmentView.as_view()),```
Now it displays all Time objects, even those which are not unique
with flask and socketio, how can I make it so I can emit something under an external event
for example, emit an event to a particular client when x on the computer happens
hey guys
can someone please help me with this problem I am facing while trying to upload files to heruko
Can we see the whole error
set up a buildpack for your heroku app
there are a lot of articles and docs on how to do it
is it alright to post here a reddit thread in which I asked for help?
def load_user(acc_id):
return accounts.query.get(int(acc_id))```
anyone can help me with this error on this code?
I bet you wanted to write acc_id()
or else, whichever code is calling this function needs to do something equivalent
oh now that mistake has been solved, but another has popped up
however it is an int, even in the database
hm, what code is emitting that error?
I don't believe you
if it were an int, the error message would say TypeError: 'int' object is not callable
I bet it's a string that looks like an int -- namely, a bunch of digits
How are ur models set up ?
before this was db.session.query(accounts).get(int(acc_id))
my models
there are with automaps, but i've tried also manual
like this
Have u tried to access ur models outside of login_manager to see what type it is or so
I know im asking stupid questions but this looks stupid u got it set as integer
in db
yes i've tried in the flask shell, if i print all accounts by query, it prints all the entity, with all the attributes, but if i specify only acc_id, or another attribute, it tells me that it is not defined with error
I can just suggest yo to use etc alternative id
There is a bit of that in flask documentation user.query.filter_by(altenrative_id = user_id).first()
also change load_user(user_id)
with load_user function you are not loading given user into session
it loads it from session by user id
I'm trying to learn flask, but when I make changes to the string literal that the "/" route returns, it doesn't update on the page unless I restart apache
How do I make it so that changes like that in the python source reflect immediately?
I'm using passenger on apache to host the app
that's pretty common, it's why people use built in flask server for development
Is there any way around that though?
No, because no one running in production would want that
there might be a dev mode
Can anyone refer me to any framework built with flask with a micorservice architecture deployable with Kubernetes or Docker Compose? The framework should have login, log out, reset password, user service feature e.t.c.
There is nothing special about being a microservice, so any flask setup with a bunch of modules will do.
If you are looking for something "batteries included" - try django. It works well enough for majority of uses.
If you are looking for something "batteries included" - try django. It works well enough for majority of uses.
@candid basalt Thanks. Can you recommend a flask setup- so any flask setup with a bunch of modules will do?
Pretty much.
Microservice is architectural approach, it has nothing to do with the webserver itself or the way it's set up.
Microservice is architectural approach, it has nothing to do with the webserver itself or the way it's set up.
@candid basalt Thing is, with micro services, you have a bunch of redundant codes, each service would need to be written to return json. If i were to take a monolithic and rewrite, it'll take some time. Wondering if there is any ready-made repo somewhere.
You can return json with django, it will work just as fine.
It will be slightly heavier then flask, sure. But will save you tons of time given what it provides.
And given you still do need things like login/logout/pw reset etc.
yea. I see your point. I have been side-stepping django for a while. I guess I have to pick it up.
I'm not aware of such flask-based frameworks though. So may be someone else will have a better idea.
I'm not aware of such flask-based frameworks though. So may be someone else will have a better idea.
@candid basalt thanks
You are very welcome. If you get any non-googlable questions - feel free to ask. We'll help any way we can.
You are very welcome. If you get any non-googlable questions - feel free to ask. We'll help any way we can.
@candid basalt thanks
@edgy kraken both flask and django return json, both can be encapsulated within containers without much fiddling and i would even say django has much more redundant code than flask
You can have one flask server in a container and then just scale it up
I don't get what you think by rewriting all services to return json
{% for img in image%}
<div class="filters-content">
<div class="row portfolio-grid justify-content-center">
<div class="col-lg-4 col-md-6 all art">
<div class="portfolio_box">
<div class="single_portfolio">
<img class="img-fluid w-100" src="{{img.Image.url}}" alt="">
<div class="overlay"></div>
<a href="{{img.Image.url}}" class="img-gal">
<div class="icon">
<span class="lnr lnr-cross"></span>
</div>
</a>
</div>
<div class="short_info">
<h4><a href="">{{img.Title}}</a></h4>
<p>Vexel Art</p>
</div>
</div>
</div>
{% endfor %}
</section>
Can someone help me it doesnt appear as i want
Why does the picture of Beauty isnt appearing
@late gale check if the spaces in your jinja brackets fix it
{% ... %} for Statements
{{ ... }} for Expressions to print to the template output
{# ... #} for Comments not included in the template output
# ... ## for Line Statements
ur img.title and for loop are not spaced
it caused me some problems once
Oh i fixed it
Thank you
the problem was i should get ```django
<div class="filters-content">
<div class="row portfolio-grid justify-content-center">
{% for img in image %}
So ```{% for img in image %}``` be under that div
i was just playing in codes until it works
xD
Magic xD
guys, I want to add the name_surname to the "char_name" database field,
but there is something wrong, this is the form code:
name = StringField('Nome', validators=[DataRequired(message="...")])
surname = StringField('Cognome', validators=[DataRequired(message="...")])
...
def generatename(self):
return self.name + "_" + self.surname```
this is in the route:
char = Char(char_owner=current_user.acc_id, char_name=CreateCharacterForm.generatename(),...
this is the error
generatename is an instancemethod, it works when applied on an object with class "CreateCharacterForm"
so for example...
ahh ok i got it!
ok π
"form = CreateCharacterForm()" -> "form.generatename()" instead of "CreateCharacterForm.generatename()"
thanks π
yeah π
ok now it works π
What u guys think how good combo is vue.js and flask ?
Great combo for spa
Going to try it
Hi everyone...i need suggestions for a project using flask to boost my skill as well as my resume
Flask is not mandatory ...but Python is
I know flask so told flask....can be data science projects
@supple loom make a copy of https://teensy.info
that's why I created that site: to learn about web programming
Ace, do you play any games?
guys
although I understand several things in backend development with flask, I still can't understand what the GET and POST methods are, what they are used for and the difference between these two. Do you know a good tutorial that explains it?
I don't get what you think by rewriting all services to return json
@vagrant adder I am thinking of separating frontend, user_service, db, e.t.c. That is the level of granularity I am trying to achieve. This will allow me scale the frontend, if needed, without doing the same to other services. This repo (https://github.com/PacktPublishing/Hands-on-Microservices-with-Python) comes close but still a lot of work to be done.
You can have one flask server in a container and then just scale it up
@vagrant adder Thats one way of doing it.
that's only way of doing it according to docker rules and specs
that's why people don't run all their stuff inside one container
that's why people don't run all their stuff inside one container
@vagrant adder Thanks
@zealous siren yes i do...and it will be awesome to create one
@quasi ridge will do when i get home
Anybody here used FastAPI + Starlette? If so, how did you fix CORS policies errors? I already added the CORS middlewares, but it just doesn't work at all :/
hey! does anyone ever use the
django-schedulerfrom : https://djangopackages.org/grids/g/calendar/ ?
@timber sentinel I've asked this last Thursday, anyone?
Anything that has to do with scheduling and calendars.
@quasi ridge what is that link you gave me?
@supple loom it's a URL shortener. You paste a URL into the box, it returns a shorter URL that goes to the same place.
Following the tutorial of coreyMs about django, i encouraged the following problem
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
img = Image.open(self.image.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.image.path)```
This is an overwrite to the models.Model save method
Which should save the image resized
but when i upload an image it doesn not rescale it, altough its bigger then expected
@quasi ridge ohh you mean i should make something like that?
ya
I consider that somewhat advanced, but you can dumb it down (by, e.g., not using AWS for the database; just use sqlite)
you can omit the recaptcha, if you're not exposing it publicy (I hate the recaptcha, but without it, 99% of the requests are hackers)
does anyone know what is my problem?
@quasi ridge can i get link to your code?
@supple loom Oh god no, don't get into game develop, see if your favorite game has API, read it and write some data to webpage
ha ha
defracted, never got it working, shoved it behind the load balancer to resolve the CORS issue
my fav games are way too big
What game?
DOTA: Defence of the ancient
Yep, there is stat API
Never used it but read it and generate a page
Thatβs a good project to show off
Hi everyone...i need suggestions for a project using flask to boost my skill as well as my resume
Iβm giving you one
please elaborate
How hard is this? Using flask, build a webpage that displays stat data from DOTA
stat data?
ohh
Or how bad you are being jungler
okay
nice ..there is a whole API for interacting with game coordinator
how much time should i take to build this ?
i have a flask app that is already currently scanning a url, scraping the data and anywhere from 3 to 7 images, saving said data in the database and uploading said images to their project base subfolder (base folder is previewimages then after that for each company another subfolder - example: previewimages/g4g/all the images for that company go in here) -
i want to be able, in flask admin, to display these as thumbnails in their views table, but they are not in the static folder. is there ANY way to do this or am I going to have to move everything around (there are over 4,000 images btw)
Which chromium-based browser has the best dev tools?
I only run FF on my computer but need to install a chromium-based for testing. Personal favorites?
either chrome or firefox
So far I think I can go with Chrome, Brave or Vivaldi. Though there's also the new Edge.
brave is still behind those giants
In terms of Dev tools you mean?
yes
hmm interesting.
firefox has some font issues with consolas and that crap
I was told the developer edition of Firefox is ideally the most obvious choice for gecko-based development.
I just don't really like Google's Chrome though it's a necessary demon - wish there was a chromium based browser stripped of every bloatware.
Is canary considered stable? Sorry I have very little idea bout it
me neither tbh π
@supple loom step 1: go to https://teensy.info step 2: click the "Fork me on Gitlab" ribbon in the upper right step 2: Hint: it's https://gitlab.com/offby1/teensy/
Known as "pyramid-tinyurl-doodle" on github. A URL shortener visible at http://teensy.info
I'm trying to upload multiple images with Flask but every time I use request.files.getlist(key) I only get the first image?
How do I accomplish multiple image upload
Request payload states that the key/name is name="file[0]"
@heavy coral do you use same models for images ?
i mean for all images
if you do add something like this
this last one is quiet messy i did this project while ago and used one image field for each image so i have 3 of them so you just need to pass that url to markup , but find a way to locate subfolder for reach image should be possible and then instead of that f'static/images/ u could have something like url_path that would be just a path to location of ur photo
Why can you call a function before it's declaration in JavaScript?
Hi. Does anyone have experience with Lektor?
I have a sass folder in my root dir, but it's being added to my assets folder when I run a build
Not a clue why
Oh. Never mind. I was generating a css.map
Hello,
I want to get advice from people with experience. I have a situation where I have a database (mongodb) and I am required to build a dashboard to interact with the database (mostly output -> graphs, tables, etc..). The database has some time series collections and some other static collections, and it is being updated from other separate processes. I want to separate concerns if I can. My current thinking process is to build a REST API (flask, fastapi, tornado, etc..) and then use some external dashboarding tool to just create fancy graphs. Is this a good design? if yes, what should I use to build the UI part? how should the API for graphing things look like (I am assuming it should be a bit different than api/resources/ or api/resource/_id).
REST API is good, as for dashboard, not sure
a BI tool might be able to consume the REST APIs to make a dashboard
Hi guys so basically I have a django-rest-framework & react app going on and im currently working on the password reset feature.
The shit that I'm having trouble with is how to customize the email reset link to point to my frontend page where it shows the new password and confirm password page.
So essentially - how do i make this link http://localhost:8000/accounts/reset/MQ/<token>/ that I'm getting from the email to point to <frontend_url>/password/change
or maybe even http://localhost:8000/accounts/reset/MQ/<token>/ to http://<frontend_url>/accounts/reset/MQ/<token>/
I don't understand. Don't you have complete control of the URL that you put into the email?
@native tide so sorry I just saw this - yes I do - I set up a db model with the following:
__tablename__ = 'imageurls'
id = db.Column(db.Integer, db.Sequence('imgurl_id_seq'), primary_key=True)
pid = db.Column(db.ForeignKey('patterns.id'), index=True)
# url = db.Column(db.Unicode(150))
url = db.Column(db.String(255, 'utf8mb4_unicode_ci'))
is_main = db.Column(db.Integer, default=0)
pattern = db.relationship('Pattern', primaryjoin='ImageSet.pid == Pattern.id', backref='imageurls', lazy=True)
def __str__(self):
return self.url
def __repr__(self):
return "<Image(imgurl='%s')>" % (self.url)
and have a m2m relationship with the pattern table which holds all of the pattern info
but the problem is that the images are not in the flask dir - they are in another dir that I have a few other big (ok big for me at least) scripts running and so since it's not in the static dir I'm just..falling short on how exactly to implement this π¦
@quasi ridge i have no idea. Im using django-rest-auth and i have no idea how to customize the url
oh my god duh - i have to set it in django-admin smfh wowowow
π
epitome of programming - am i right π
Why can you call a function before it's declaration in JavaScript?
Yea, let's call it "feature" π
π
Hey. I'm developing SPA with django+react and I want to deploy it locally on Windows 10. What servers do you guys recommend? Using Django + PostgreSQL
I need something lightweight and secure since not a lot of people will have access to it (10 at the most)
@quasi ridge lol...thanks
Just an offtopic , im quiet amazed how programming forums and groups are nice and opened. I started with python basics in july i managed to create an 3 web apps so far , but all of that would be so harder without having an input from some of you gals here. Really good to see that people strive to help others to become better . Props to all really
After that does anyone have any material that covers flask / vue.js topcis ? i just found one project that is sort building TODO list
Ok
It's a feature
I have a website that i put on the heroku servers
It loads really slow
Even though i didn't put any
Photo's
if it's free tier, there may be a big delay processing the first request, while they load your code from "disk" into "ram"
well, it could still be wrong; I'm just guessing. I don't use heroku
but it might be worth your time looking at their docs again
Are there any other i could use
Maybe it's just heroku
Other hosting server you have experience with
?
I don't use that sort of hosting
I've used lambda, and ec2, but those are very different
as far as I know, heroku is as good as it gets
ohkay
I read something
About HTTP caching
Heroku doesn't support HTTP caching by default so i need to configure it in my app
But u don't know how.
What?
Uhm
I guess client
Client side HTTP caching
Yes
The website should display faster.
Client side is handled by browser
so unless you send no cache header, browser should cache
ultimate fix is going to be "pay for hosting"
Great
DO is only 5USD
@native tide so heroku has free tier which has limited hours
and they solved that by putting your server to sleep if there is no communication with the server in 30 mins
so upon first request to the site, heroku has to clone and start your server from scratch since their server solution has non-persistent filesystem
so upon 1st request its hella slow but when it starts, it's usable
i see!
that's good to know
so
within 30 minutes
look'
i open the website now,
so when i go back in ten minutes
it should load fast
cuz the server didn't close it
is that so
?
that is correct
cheers
i just came up with an idea
that i can create a bot that goes on my website every 29 minutes
is that even possible?
cuz i hear a lot of bots these days. ex: the ones discord servers have and chat bots
If i can create this bot, my website will always load fast.
How do you define a pop-up box with text that comes up when you click a button?
use the onclick fucntion @dawn jackal
for example when i click on this hello button, a box will appear that says: 'hi'
<button onclick="alert('hi')" >Hello</button>
Hi all, I had an idea for a web at work today.
Before I start to put the idea over I wanted to find out how best to approach it.
From my sources ReactJS seems to be a dominant force.
I need to build a web UI with DB backend to auto some processes and send email.
The company I work for are mainly an Microsoft shop and starting to move to Azure.
I am intersteed in using Python as it would simple for other people to learn but not really heard anything about Python web apps.
@native tide yes that is possible but you would run out of working hours
Can someone help me with flask-socket.io?
!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.
β’ 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.

What do you mean run out of Working hours @vagrant adder
i am guessing something like, your server can be active for 5 hours a day in the free plan, or 40 hours a week or whatever
and when you do that, you will consume the hours you have in the free plan
so the server wont be able to be live until the timer resets
Hey guys, can somebody help me with this question. When using Keep-alive connections, what kind of thing server has to do when keep-alive timeout has expired? Just close connection or somehow notify the client and only after that - close connection? Can't find anything regarding this on internet
@native tide Just make a cloud/lambda function that does a simple request to your website every 25min
@native tide so, your free dyno on heroku has limited hours to work per month
It's 550
That's why your dyno goes to sleep after certain amount of time(30mins)
probably 500, cause 30*24=720 π
So if you get 1000 hours dyno per month you can keep one dyno running the whole time as long as you ping every 30 min?
Or will that count as abuse?
I see nothing about abuse in their doc, they do however recommend turning off pinging/monitoring services to save hours
Hi, I have a flask question
I have a small script that writes to a text file when a user accesses a page
if a second user accesses the page while another user is reading or writing to the file, will this cause a problem?
I imagine I'll get some kind of interesting error code
that's just an IO error yeah
w
Try using a then it just adds to the file
Thats how I do it a log.txt for a simple logging who visit my flask site
Are you writing to the same file?
I'm planning on setting up one file that shows the most recent access time and session ID
Right, it almost appears like you're going for some custom logging system
then as long as no one has written for 0.1 seconds it writes to the bigger seperate CSV
yeah exactly
I think Flask has special support for Python's built-in logging module
Maybe that's a good alternative that would give you an easily extendible and robust logging base
You could even "just" use the logging module itself
I have an external site that calls my flask website and provides some user info for storage on the flask server. My goal here is to store it while also making sure the call can't be done a billion times by a malicious user
is logging the right choice?
Ah, that sounds like a different use-case than regular logging
You're basically looking to apply some for of rate limits for different users
There are other solutions for that, but I'm not sure if flask has them built-in (Flask takes a more minimal/batteries-excluded approach than, say, Django)
There are a lot of plugins that would give you this out of the box though
exactly, I was reckoning that I might use some kind of time and user que thing
I'd imagine that something like this: https://flask-limiter.readthedocs.io/en/stable/ would do the trick nicely
that looks handy, especially the shared limit
How can I use Flask within my own class? I basically want something like```py
from flask import Flask, redirect, url_for
class App:
def init(self):
self.admin = False
def run(self):
app = Flask(__name__)
@app.route("/")
def home(self):
return "<h1><b><u>Hello World!<h1><u><b>"
@app.route("/<name>")
def user(self, name):
return f"Hello {name}!"
@app.route("/admin")
def admin(self):
if self.admin:
return "Hello Admin!"
return redirect(url_for("home"))
if name == "main":
a = App()
a.run()
* Serving Flask app "app.py"
* 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
Usage: flask run [OPTIONS]
Error: Failed to find Flask application or factory in module "app". Use "FLASK_APP=app:name to specify one.```is the output I'm getting
I was typing flask run
I seem to have fixed it all up now though
from flask import Flask, redirect, url_for
class App:
def __init__(self):
self.admin = False
def run(self):
app = Flask(__name__)
@app.route("/")
def home():
return "<h1><b><u>Hello World!<h1><u><b>"
@app.route("/<name>")
def user(name):
return f"Hello {name}!"
@app.route("/admin")
def admin():
if self.admin:
return "Hello Admin!"
self.admin = True
return redirect(url_for("home"))
app.run()
if __name__ == "__main__":
a = App()
a.run()
```is working as intended
So I think I'm good now, thanks though @native tide
Yeah flask run is looking for a folder called app
Or also looks for app.py
So from the code you posten it seeems to want to be run with python yourfile.py
The old way of running flask
Is there any a need of creating a flask app in the way "TizzySaurus" did (as a Class) instead of the standard way?
The main reason I did it is so I can pass variables around easily @tranquil robin
Like the self.admin
I'm like 30min into Flask tho so there might be a better way idk
And global variables are such a big no no in python
:~)
i wanna make a validation arrow in a form without javascript is this possible?
So when its out of work hours, the server to my website shuts down? For that month?
If you are talkin about heroku, then yes. If you have used up your hours then it will be forced to sleep until next month
i fully get it now
for my website to stay active i need to pay atleast $7 per month
If you register your creditcard you get 1000 hours per month
So the one app can run constantly
But it will go to sleep if its not been visit for 30 minutes
But you will not run out of hours π
that without pay?
Yeah, I think so. It just says they just need a credit card on file. Havenβt tried it out yet
ok
Itβs explained here: https://devcenter.heroku.com/articles/account-verification#when-is-verification-required
π
Hello everyone
I been trying to use my Gmail account to send emails to other users in my website, I enabled "Allow less secure apps" for my Gmail account and I still got
ConnectionRefusedError: [Errno 61] Connection refused
Yesterday I asked this question but back then I wasnβt sure what the problem was, after looking into other solutions I just found out that every other chap is able to use Gmail for sending emails but it doesnβt work for me.
I followed this tutorial and did exactly as mentioned:
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-x-email-support
These are my virtual environment variables:
(venv) $ export MAIL_SERVER=smtp.googlemail.com
(venv) $ export MAIL_PORT=587
(venv) $ export MAIL_USE_TLS=1
(venv) $ export MAIL_USERNAME=test@gmail.com
(venv) $ export MAIL_PASSWORD=test-test-test-test
The account that I used in MAIL_USERNAME variable is the one with βLess secure Appsβ [Enabled]
This is the code I used for sending Emails to ANY email address:
from app import mail, app
from flask_mail import Message
msg = Message('Samba Day', sender=app.config['ADMINS'][0], recipients=[βquestion@stuckoverflow.comβ])
msg.body = 'Samba Jr'
msg.html = '<h1>Samba</h1>'
mail.send(msg)
If there is no solution to this what other free mail service I can use for this?
There are no free email services and GMail is not going to let you blast stuff out either, look at AWS SES
guys, how can i manage in flask web app the "Accept" and "Reject" submit buttons? I can only do this with a single validate_on_submit, but this time, the submit options are two
@zealous siren OK, so what if I want to use python fake smtpd server for emails?
I am using it already for receiving emails, its on localhost:5151 but I need to test it throughly with another smtp server that I can use to [Send] emails
Now I looked it up and seems like python-smtpd cannot be used for [Sending] stuff
It's not necessary for now to [buy] things, I just want to learn how to do all this on localhost
In short: Is there something i can use to send emails to my-fake-smtpd ?
something as in software or as in flask extension
i think flask extension would work since i am working on this blog project
fatcat, then use fake smtpd server
it should accept emails, it just won't send them
so they get accepted and then throw into /dev/null
[SENDER]
in case of localhost my settings will change to:
(venv) $ python -m smtpd -n -c DebuggingServer localhost:8025
(venv) $ export MAIL_SERVER=localhost
(venv) $ export MAIL_PORT=8025
[RECIEVER]
from app import mail, app
from flask_mail import Message
msg = Message('Samba Day', sender=app.config['ADMINS'][0], recipients=[βAnother_fake_serverβ])
msg.body = 'Samba Jr'
msg.html = '<h1>Samba</h1>'
mail.send(msg)
What should I put in ['Another_fake_server'] @zealous siren ?
rForm = RejectApplicationForm()
if aForm.is_submitted():
flash('1')
elif rForm.is_submitted():
flash('0')```
guys why it flash always 1?
example.com, where it comes from?
my sender is already up and running but the receiver or recipient is not up and running
i need another tool for creating a fake recipient
One of them is up and running (for sending emails):
python -m smtpd -n -c DebuggingServer localhost:3121
This is the code for sending:
from app import mail, app
from flask_mail import Message
msg = Message('Samba Day', sender=app.config['ADMINS'][0], recipients=[βmail@example.com'])
# that doesn't because @example.com is a domain on WAN
# i need to change that to some other receiver
# i had tried localhost:9999 but it didn't work
msg.body = 'Samba Jr'
msg.html = '<h1>Samba</h1>'
mail.send(msg)
sorry if my question are confusing
its more confusing for me
i am planning to jump to another chapter but that way my app wont work at all because my code is different from the author of Flask tutorials
there's something wrong with the quotes you're using
mail@example.com has a strange quote at the beginning
I don't think so, I am looking so close to my screen, I copied and pasted a quote from your sentence above, seems like OK to me
β <-- this is not right
even the syntax highlighter freaks out
βmail@example.com' the starting quote is not the same character as the apostrophe at the end
seems like you were right, thank you, but still, this code my friend doesn't work, I dont know how the author made it works
seems like i would need to go shopping for this chapter, i am skipping it for now, thanks everyone for giving time
guys, why this code flashs always 1?
aForm = AcceptApplicationForm()
rForm = RejectApplicationForm()
if aForm.is_submitted():
flash('1')
elif rForm.is_submitted():
flash('0')
-----------------------------------------
class AcceptApplicationForm(FlaskForm):
submit = SubmitField('Accetta')
class RejectApplicationForm(FlaskForm):
submit = SubmitField('Rifiuta')
----------------------------------------
<form action="" method="POST">
{{ aForm.hidden_tag() }}
<p>{{ aForm.submit() }}</p><br>
{{ rForm.hidden_tag() }}
<p>{{ rForm.submit() }}</p>
</form>
if i submit rForm, it flashs 1 anyway
@cloud path, you have 2 submits in the same <form> element. You probably want 2 seperate <form>s
How can I find the cause of the problem when JS is not receiving a socket msg from flask?
They were contacting each other just fine, but on one of the socket.on("event") JS is just not receiving anything, Flask is sending everything just fine
why does my live server not load
vs code has an extention
live server
an addon
it takes forever to load
it wasn't acting like this before
i'm very confused
i tried reinstalling it
still doesn't work
@native tide does the live server, work with JS? or only HTML and CSS?
π« π€¦
the problem was my code
i have been struggling for three hoursπ
function sum(limit) {
let amount = 0;
let i = 0;
amount = 0;
while (i < limit) {
if (i % 3 === 0) {
}
}
return amount;
}
console.log(sum(10));```
I feel you π , been struggling with a JS issue for half a day and it turned out to be the location of the function definition π
lol
Looking for someone with web development experience to do some paid work. PM me.
6. No spamming or unapproved advertising, including requests for paid work. Open-source projects can be showcased in #show-your-projects.
Hey all! New to the channel, seems like one of the few Discord channels that's active and not overrun with marketing / ads.
Had a quick question. I've seen all of the buzz around static site generators, and the concept definitely makes sense if you are trying to build a decent dev workflow for simple content sites (basically a CMS without the overhead of a CMS).
But can static site generators (SSG's), like 11ty or Panini, be used /w Python frameworks like Flask to create websites with User Logins?
I've seen a couple articles mention using SSG's in conjunction with a web framework like Flask to serve the flat HTML pieces as static assets via an Nginx server, and only serving the dynamic elements via the WSGI server.
I guess my questions are:
- Can SSG's be used by themselves for websites that need a User Login?
- If not, and you'd have to somehow pair the SSG piece with the WSGI server (Flask) piece, is this a common practice? Are there benefits?
- I might be way off on all of this... (tried to do a bit of research before throwing up the white flag and asking for help). What am I missing? What would you recommend?
My apologies if this is in the wrong section or anything! Cheers.
@languid briar when you say a static site with a user login, what precisely do you mean?
This project is for a client that is a barbershop with 10-15 locations. 80-100k customers, the goal is to start tracking them by creating User accounts and Client dashboards listing their past bookings, etc.
CRM is managed by a third-party service (we will have the Users log in via their API, then also store a MongoDB table with their KPI details so we can personalize pieces of the site).
hard to believe there aren't canned sites like that
they don't want to use Squarespace?
hey @half summit, if you need help with both Python and JavaScript, maybe this is the channel if you want
may I ask you to set a different nickname on this server?
ok
so i need someone to help me rewrite a javascript program to a python
you're welcome to ask questions if you get stuck on certain parts of the project, but just asking for someone to do the work with you isn't really allowed as it falls under recruitment which isn't allowed in the community
@languid briar
Ssg's are used to generate static content, there is 5% chance that it allows user session and logins, most likely you'll have to do it yourself
People often pair ssg with php or javascript since they are certifiedβ’ web dev languages
Pelican and Lektor are commonly used with python
Pelican's primary templating engine is jinja which is used for flask templating as well
@half summit
I don't think you can directly transpile to python
But you can evaluate js code in py
Search for js2py
what am I doing wrong with Handlebars here?
HTML:
<!-- handlebars -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.2/handlebars.min.js"></script>
<!-- Handlebars template for channels -->
<script id="h-channels" type="text/x-handlebars-template">
<li>{{ channel }}</li>
</script>
<!-- in the body -->
<div class="side-clist">
<ul id="chanlist">Channels
</ul>
</div>
Javascript
var template = document.getElementById("h-channels").innerHTML;
var templateScript = Handlebars.compile(template);
var html = templateScript(payload);
document.getElementById("chanlist").innerHTML += html;
the payload looks like this:
{code: "1", channel: "testname"}
and when I console.log(html) i get this
<li></li>
Try channel.channel
Tried hard refreshing in the browser?
@quasi ridge The idea is we want to be able to track customers more closely. By firing booking events into mixpanel and a MongoDB, we can grab past histories and personalize each page of the website based on the visitor's booking history. For example, if it's their 3rd booking, we can show a different home page pitching a membership. Give people the option to re-book with their favorite stylist, promote products they've purchased in the past, etc.
Sounds like an SSG isn't viable for this - thanks for all of your guys' help!
@vagrant adder figured it it, had to add {% raw %} cause I am using jinja
Noice, thanks for pinging
π
I have a css question
I'm using object-fit: cover and object-position: to crop an image
And if I set the width of the img to 50vw or 50%, I'm unable to reposition the image horizontally
Any idea why?
anything I can improve here
from django.shortcuts import render, redirect
from .forms import Payment, NewCard
from .models import Transaction, Card
# Create your views here.
def index(request):
return render(request, 'index.html')
def new_card(request):
if request.method == 'POST':
form = NewCard(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
request.session['id'] = instance.id
return redirect('/payment')
form = NewCard()
return render(request, 'new_card.html', {'form' : form})
def payment(request):
try:
card_ins = Card.objects.get(id=request.session['id'])
except (KeyError, Card.DoesNotExist):
card_ins = None
if request.method == 'POST':
form = Payment(request.POST)
if form.is_valid():
product_price = float(form.cleaned_data['products'])
if product_price < float(card_ins.cc_amount):
new_cc_amount = card_ins.cc_amount - product_price
new_transaction = Transaction(card=card_ins, price_paid=product_price)
new_transaction.save()
card_ins.cc_amount = new_cc_amount
card_ins.save()
return redirect('/')
form = Payment()
return render(request, 'payment.html', {'form' : form})
def transaction_history(request):
all_entries = Transaction.objects.all()
return render(request, 'history.html', {'all_entries' : all_entries})
Making a flask API (made with flask-restful) with some schemas (made with flask-marshmallow) and trying to implament PATCH. I have a basic wip schema that will we extended looking like this: ```py
class PostPatchInnerSchema(ma.Schema):
"""
Inner contents for PostPatchSchema.
This is similar to PostPostSchema but all fields optional
"""
title = ma.String(required=False)
body = ma.String(required=False)
is_private = ma.Boolean(required=False)
header_img = ma.String(required=False)
class PostPatchSchema(ma.Schema):
"""
The PATCH schema for an existing post by a user
"""
post_id = ma.Integer(required=True)
changes = ma.Nested(PostPatchInnerSchema, required=True)
But the problem is that sending a request using the `requests` library using this schema fails. Here is the approx requests i'm using to call:py
requests.patch(
f"https://127.0.0.1:5000/api/post/",
data={"post_id": 2, "changes": {"title": "New title!"}, # valid data
headers=self._generate_headers(), # auto gen headers from token stored
)
hi!! how do u upload project to the github repo using github api ??
You don't use the "github api", as such. You use Git itself to do that.
im trying to automate it
like for multiple project to create its own repo and upload files
i can do that with shell scripting and using selenium too but i want to use github api for that
more like i want to chuck in the project to its specific repo using github api
Not sure how that's useful, considering it'll just have a single commit?
i can chooose to commit chunk of files like i want
anybody know another reason i would get a 406 error even when using the 'Accept': '/' header
'Accept': '*/*'
can only think of the value u posted doesnt work
hwo did u add theheader for the session ur posting
header = {
'User-Agent': 'curl/7.55.1',
'Accept': '*/*'
}
url = 'https://10.10.1.1/api/sonicos/auth'
response = requests.post(url, auth=('admin', 'hello'), verify=False, headers=header)
u dont doo it that way
so u create
session = requests.Session()
then session.auth(username, password)
and check the session.get(url).status_code sud be 200
oh and session.post(url)
before getting it
okay cool, thanks! im gonna try and put it together that way
nw u post before getting session url
anyone has use github api to post projects on repo ?
!subscribe
?
oof finally did it lool
Hi all
I'm using DRF with React. Can someone help me with validators?
Here's a simple one I have:
def phone_validator(value):
if len(value) != 9:
raise serializers.ValidationError(_('Validator|Phone', 'Phone must be 9 digits long'))
I also would like to send a message to React so it can respond to the user appropriately
Can't seem to find it in docs
All I get in browser console is Error: "Request failed with status code 500"
I am working on a small project (Flask-socketio backend -- JS socketio frontend) using the backend response I am creating HTML elements using handlebars, but the event that creates the HTML elements gets run twice when I refresh the page, and I end up with HTML duplicates.
For some reason this file and line ( Line 83 -- https://hastebin.com/olikipoqul.js) runs when my JS script creates the HTML elements, and in the debugger it stays stuck there for a while.
Any idea what file this is and why this is happening?
PS: if needed this is my JS file (https://hastebin.com/iborufasez.js) the HTML creation happens in the lines (42 - 53)