#web-development
2 messages ยท Page 43 of 1
@heady thorn There are definitely flask/react frameworks oriented around charting/graphing. But if you're building things yourself, I'd reccomend checking out FastAPI
It seems very nice for this sort of thing
Thanks @rigid laurel awsome. So flask +fastapi +Vue is ok?
No, just FastAPI+Vue should be fine
FastAPI and Flask are doing the same thing
FastAPI is sorta a nicer version of Flask if you're only doing Rest
which I assume you are with Vue right?
I haven't looked at integration with backend. I kinda figured flask would provide API framework
And I'd just suck it into Vue
If that makes sense :)
Yeah, both Flask and FastAPI can do rest-APIs, just FastAPI is a bit nicer for it IMO
Great thanks v much for the recommendation. Hey, whilst I got ya...
Is python really awsome for the maths/datascience stuff?
Everyone says it is sooo... Yeah prob makes sense to use it as the backend for a data project.
I've used the datasciencey stuff a little myself - and I don't mind it. But the way you use datascience stuff is quite different to how you use normal Python
I've not used R or anything similar, so I can't provide a comparison
Nice. I might check out jupyter notebooks too I hear also good
Right thanks Charlie. And thanks for the warm welcome to the community ๐
Jupyter notebooks are the one thing I don't get. Maybe if you're demoing something to non-tech people, but for the most part I just find them irritating. But good luck with your Python adventures
๐ค๐๐ค
How can I turn an html string into a variable
If a user called SneakyKiwi was logged in this should be SK | SneakyKiwi
Do I have to use a method?
Hi guys im using flask. Is it possible to use uploaded file without saving it ? For example recieve a photo then read characters from it (ocr) and send back those characters; I dont want to save the image.
I suppose you could create an endpoint that just returns those characters in the response to the POST or PUT
but of course the photo would need to be somewhere in order to do OCR. Maybe just memory
@app.route('/', methods=['POST']) def upload_file(): photo = request.files['file'] oc = ocr(photo) return jsonify(oc)
gives error: im = cv2.imread(img) SystemError: <built-in function imread> returned NULL without setting an error
sorry, I have no idea what "imread" is or how it works
it looks like that function requires a file
which would answer your original question.
it also looks like that guide was written very sloppily, so I wouldn't put too much faith in it
So i guess i will stick to saving then deleting it after ocr...
you might even use the "tempfile" library
I have this server deployed to aws elb and the ocr results are different than when i run it through aws and through localhost. Its 100% the same code but results from aws are much worse, is it possible that files are getting compressed when uploaded to aws? I haven't set anything to do that
its a service provided by amazon
used to host servers etc
idk how accurate my explanation is but i think thats enough
Amazon Elastic beanstalk
well, I still don't know why you're seeing that difference.
I am using this:
def registerhandler(username, password):
pw = generate_password_hash(password)
print(pw)
print(check_password_hash(pw, password))
ins = users.insert().values(
username=username,
password=pw
)
connection.execute(ins)
return
To register users
And this for login
def loginhandler(User):
headers = {'alg': 'RS256'}
payload = {'username': str(User.username), 'iat': time.now()}
key = read_file('privateKey.pem')
search = session.query(users).filter_by(username=User.username).first()
print(check_password_hash(str(search[1]), str(User.password)))
if not search and check_password_hash(search[1], User.password):
print('Wrong credentials')
return None
elif search and check_password_hash(search[1], User.password):
print('User {} has been found'.format(search[0]))
token = jwt.encode(headers, payload, key).decode('utf-8')
print(token)
return token
print(check_password_hash(str(search[1]), str(User.password)))
It always returns false, even though search[1] returns the hash key from the database which was inserted using registerhandler()
and the User.password is the pw used by the user to signin
I cant get it to return True
@quasi ridge i figured it out, i forgot to download some additional data to the ocr program on the server, that i had on my local machine
gรผd
Hi.
I'm trying to execute a script in PHP
Then return a variable to PHP
Is it possible?
While I continued reading an article about prototypes, I stumbled upon a final question. When a object searches for a property that it does not have, its prototype will be searched for the property
But what is IN the prototype that it is searching
???
More properties from its parents?
It is confusing
<Javascript - Web Development>
Hello
I have a class with a variable self.passwords
after populating the passwords and having a route return the passwords, every few requests properly return the passwords but occasionaly one request doesnt and it returns []
here's a video example, im constantly refreshing (might not be able to tell) and at the end, data is [] but then goes back to being ["testpassword", "testpassword1"]
anyone know why this is happening and how to fix it
https://stackoverflow.com/questions/60470810/class-variable-returning-incorrectly-python-flask
here's the stackoverflow i posted, more detailed
What is manager.passwords?
From what you have said on SO, you are not using a DB
therefore, probably no proper encryption
Please explain what you are doing here
because it sounds like those 10k people will have a very bad awakening
@quartz lily
well
Just to let you know, I fully concur with what has been said on SO. Use a database
it's just something in a class
the problem is if I use a db it's so many reads to it
cause I have to constantly keep reading to the db
so?
that is what databases are there for
Also, with caching you can minimize all that
if you are managing the servers yourself, add nginx as a reverse proxy and use apache as app server with mod_wsgi
then an extra database server
But anyway, serving a website to 10k people a second is no trivial task
So, what is this manager?
how do you store passwords?
well it's for restocking my product
and I do have it in my database
a restock model which has a password, copies amount, and an IP from the checkout
but I use the manager class for handling all the restocks
A http request works this way: The user connects, he gets the data, then disconnects. All scripts are unloaded, the context is lost.
So, when you try to preserve data between sessions, you got 3 options
1.) Database
2.) Javascript Sticky Session
3.) Dedicated Session Server with tons of RAM to store it there
With 3, this server can NEVER go down
Picking 1, with every received request, you must read the database
yeah so basically each time someone loads the home page, it would need to make a check to the database
yes
isnt that a lot of reading
it could be 10k per second actually.
What kind of setup do you have?
for a span of 10-15 min
some pythonanywhere server, I can share the specs in 5 minutes
ok, then I assume there is sufficient bandwidth between the instances
in that case, 10k isn't a lot
A way to save computing and bandwidth, is to use database views
those are prestored sql calls, which save tons of time and bandwidth
ALso make use of https://pythonhosted.org/Flask-Cache/
Hi, I am creating a website using flask
I have html elements that react with javascript. I want to pass data from these dynamic elements to flask, do the necessary computing and then return the data to the html
without refreshing the website
How can I do that
jquery
make a request to a route which does all the necessary computations
or ajax
and then from your route, return the data
its just an ajax get request
or post request rather
you post data to your flask route, and in your route do whatever computations and return
hm ok
if you don't know how to use flask routes i would suggest looking into those first
cause those are the basics
will this return the value of the element?
var number = document.getElementById('clicks').value
say the value was '500'
Yeah
That works
depends on what element clicks is though
and thats more JS, it's much easier to use jquery
function submit(){
const http = new XMLHttpRequest();
https.open("POST", "/lolcreator");
https.send;
}
This should work
but it doesnt right?
dude ive not seend that before
u arent doing it the way i do it, which is much easier tbh
i said ajax
ajax.get
also you arent posting any data so that would also cause an error
i am doing it for test
If you need bidirectional communication, use a websocket, not ajax requests
@rustic pebble
I need this:
Send request to a flask path -> flask path returns a string -> alert(string)
again, use websockets, then your frontend and your backend can talk to each other
without reloading
I am not rly sure how to do that either, but I will try
Or maybe rethink if you really need it without reload
another option is a rest api with the ability to POST
I really need it without a reload
why?
for ux
if you explain what you do, maybe one can help you
I dont want to get in the details of the project
My main goal right now is to be able to request and receive within the same session
else I could use cookies and solve my problem rly quick
@rustic pebble Use ajax maybe?
It looks like Kiwi is currently trying to use AJAX and it isn't working. But ajax is very probably a better solution than websockets
@rustic pebble If you post your Flask route, and the whole AJAX request that you're trying to make, it'll probably be easier to help (assuming you haven't solved it). And the fetch() API is probably the best way of making AJAX requests
If you're still looking for help when you see that message, you can feel free to @ me - I might not be able to help immediately though
anyone knows how can i send a file to my flask server with requests?
requests.post(url, files={'my_file' : open('path_to_file', 'rb'))
Then you need to have a post url on the flask backend
and access the file something like this my_file = request.files["file"]
oh thanks :)
i managed to send the file but when i recieve the file it doesnt recieve it in binary
rb
im not sure how to use it, what i did was
data = request.files['file']
with open(data, 'rb') as outfile:
print (output_path)
oh wait nvm im dumb
yep fixed it
all i had to do is data.read()
thanks for the help anyways
@rigid laurel Hi, thanks for helping me. I have 6 buttons arrayed in 2 rows of 3. The bottom 3 control the name of the top 3 by clicking them
I want to get the names of the top buttoms as they are the desired user settings
So this is a JS problem then right?
oh no
I get it
you want to post the value of the buttons over to your flask
then process them there
yes?
yup
I actually want to do this but I am not sure if that is possible security wise:
User adds the settings he wants => User clicks submit => submit posts the settings to a flask route => response is calculated by the server => response is displayed real time without refresh
None of that is very difficult to do with a little JS
But explaining it isn't necessarily easy
hm
yeah, its the kinda thing thats easy once you know it, but very alien if you don't know it
not really. I know c#
so it is not very strange to me
it just misses the linq part which i am grateful for
a high level overview is that you want to:
- use the fetch API to make the post request to flask with the new settings
- In flask respond to that with a json
- Using the fetch API, when you get a response, update the html content of what you want to change
that is what I was thinking
This is kinda my js right now
function sendpost() {
var http = new XMLHttpRequest();
var url = "/lolaccrequest";
var params = 'accnumber=' +clicks+'&server='+servers[i - 1];
http.open("POST", url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);}
this sends a request to my server
You don't want to be using xmlhttprequest
use the fetch api or use jquery
So I have been told,
I'd definitely reccomend the fetch API.
But with what you have, what is the problem
updating the content on the page?
what are you returning with flask? A json or html?
I am not returning anything, when I reload I pass this: return render_template("/logged/user.html", data1=data1, data2=data2....)
And to display data I am using {{ data1 }}
and so forth
From the client side, you need to essentially manually update only the values that you want to update
For example these left are the starters of a users first and last name
along with the username
so you'd want to return a json instead of the template
return dict(data1=data1, data2=data2...)
This is what I am doing
<a href="javascript:void(0)" class="simple-text logo-mini">
{{ starters }}
</a>
<a href="javascript:void(0)" class="simple-text logo-mini">
|
</a>
<a href="javascript:void(0)" class="simple-text logo-normal">
{{ username }}
</a>
hmm
then on the js side you select the elements you want to update
and change their values
Yup that is what I want to do
But I am not sure how to read responses on js
On python you just use data = json.loads(response.text)
and u got a dict
alert(http.responseText); --> let my_response = JSON.parse(http.responseText)
and then you have a JS object
what does let do?
oh wait
yy
ik
let me try this
I will delete the function
and redo it
function sendpost() {
$.post('/lolcreator'),
{
accnumber: clicks,
server: servers[i]
}
}
This should do the job
right?
yeah, that looks right
ish
its been a while since I've used jquery
I've mostly used the fetch api recently
I have never used fetch api beforehand
its very promisey, but its pretty good
Let me try and build with fetch api
const data = {accnumber: clicks, server:servers[i]};
function submitdata(){
fetch('lolcreator',{
method: 'POST'
headers: { 'Content-Type': 'application/json',},
body: JSON.stringify(data),})
.then((response) => response.json())
.then((data) =>{
console.log('Success');})
According to their docs
This should work
let me try it
havent used it, I was waiting for ur response
I am getting this
Although I am using it
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *client
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return await response.json(); // parses JSON response into native JavaScript objects
}
postData('https://example.com/answer', { answer: 42 })
.then((data) => {
console.log(data); // JSON data parsed by `response.json()` call
});
Try this version exactly instead - that error looks like its to do with the order in which you're doing things
That being async wont mess with the rest of the js I have on the website right?
oki
async function postData(url = '/lolcreator', data = {accnumber: clicks, server:servers[i]}) {
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *client
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return await response.json(); // parses JSON response into native JavaScript objects
}
What does that do
postData('https://example.com/answer', { answer: 42 })
.then((data) => {
console.log(data); // JSON data parsed by `response.json()` call
});
oh wait
postData('https://example.com/answer', { answer: 42 }) // This is sending the data
.then((data) => { // This is the function that parses the response from the server
console.log(data); // JSON data parsed by `response.json()` call
});
try making your request from the crome/ff console
just paste your version of js postData('https://example.com/answer', { answer: 42 }) // This is sending the data .then((data) => { // This is the function that parses the response from the server console.log(data); // JSON data parsed by `response.json()` call });
that into the console
and see if that works
Ok I fixed the request
it makes it
Method not allowed is okay, I havent configured it
Yeah, thats a problem on the flask side of things
thats because you aren't returning a json from the flask
I'm pretty sure
its just getting the default flask error
omg, I have to scrape the temp fix I made last night, it would set a jwt cookie, and decode it on the html render
omfg
which is a html 403 or whatever
its not valid json
dict
no, that will think its a set
dict('Success':'True')
that will work yeah
{'succes':True} or dict(success=True)
needs to be an equals if you use the dict() method or a :; if you do it with the literal
that should work yeah
If I wanted to print the response onto console
I would do console.log(response.json());
postData('https://example.com/answer', { answer: 42 }) // This is sending the data
.then((data) => {
// Here data is just a JS object which you can print
console.log(data);
});
or depending on which version of the code you went with
your way should work as well yeah
I am using this
async function postData(url, data) {
const response = await fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: JSON.stringify(data)
});
return await response.json();
then when you call the function, you need to do postData(url, what_youre_sending_to_flask).then((data) => { console.log(data)})
There you go, now you just need to replace that with some JS to update the content
That is one long button
<button class="btn btn-primary btn-block" onclick="postData(url='lolaccrequest', data={accountnumber: clicks, server: servers[i]}).then((data) => { console.log(data)})">Submit</button>
Do I have to make the replace functions async as well?
well, you'd just be calling it inside the then() so you should be fine to call non async stuff there I think
Soo, I will have to do .then((data) => function1(), function2(), etc)
to call the functions
but data is in dict, if I wanted to display only username I would do:
.then((data) => function1(data['username'])
?
you could do that, but its just a js object, so you'd probably want to do data.username
ooh right
damn js is fine as fuck]
If I wanted to set the data as global variables
oh nvm mb
@rigid laurel sorry for pinging. Say flask server responds with 10 usernames, I have a table which I want to update from that. I know that I can use
var row = document.createElement('tr');
But if I want to update the column values so that they match the usernames receive
received
You already have the table, and you just want co change all values in a column?
I want to add values depending on reponse count
so if 5 was received it would create 5 rows
ah, gotcha
if 10 was received it would create 10 rows
I think I got it tho let me try to write it:
var table = document.getElementById('responsetable');
for (var i = 1; i <= data['usercount']; i++{
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement('td');
var text1 = document.createTextNode(data['data1']);
var text2 = document.createTextNode(data['data2']);
var text3 = document.createTextNode(data['data3']);
td1.appendChild(text1);
td2.appendChild(text2);
td3.appendChild(text3);
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
table.appendChild(tr);
}
maybe I should do this as well:
document.body.appendChild(table)
I am making a header for my project with button links, rn I have written code in the html base file which bacically checks a current_page string with a preset string and displays a button if the strings arent equal, I was wondering, if there is a better way?
Because rn I have to rhn an if check for every button
I use this, I feel this is better than anchors since I commonly have to implement custom headers/side bars. As long as there is appropriate classes etc
I am getting : $.notify is not a function
But I have included both jquery and bootstrap-notify beforehand
Loading a script into a certain page, it doesnt seem to trigger the none-function stuff
const toplevel = document.getElementById("toplevel")
console.log(toplevel)
if (toplevel === undefined || toplevel === null) {
console.log(`Getting toplevel returned ${toplevel}`)
var elem = document.createElement("DIV")
elem.style = "width: 99%;padding: 10px;height: 25%;font-family: monospace"
elem.innerHTML = `<span class="text-warning">Unable to locate element "toplevel". Some functions may not work properly</span><br><span class="highlight-info">Expected Type: div<br>Got: ${elem}</span>`
}
function r(url) {
if (url === undefined) {
var url = "index.html"
}
window.location.href = url
}
function fetch(url) {}
if (url === undefined) {
var url = "https://ptb.discordapp.com/api/guilds/504504527093891074/widget.json"
}
}
Nothing is logged, any reason why? I need this to run at page load
hold up
i added an extra } and it broke it
i need to stick to python smh
Little Question is it possible to give a php variabel a value with a Python command
python and php live in different worlds, but you can run python commands through a shell using php and read stdout
@haughty saffron what exactly are you trying to do here? your fetch function is doing nothing atm
๐
Would anyone be able to help me with this? https://stackoverflow.com/questions/60473787/wrong-timeline-appearing-with-plot
In regard to the Django polls app:
I tried adding dunder methods like __lt__ and __eq__ to my models so that I could sort my objects by a numerical property. It works fine... until I open up my admin site and attempt to save a new object there.
https://www.ppaste.org/H1u14MQ9u
I have verified that commenting these two methods fixes it and the admin site resumes working.
You will recognize this example as the polls application from the official tutorial. I have merely added these methods because I thought it was a good idea. It is otherwise exactly the same app from tutorial 1 to 7.
https://docs.djangoproject.com/en/3.0/intro/tutorial01/
I'm curious to know what is under the hood that causes it to break the admin site functionality.
Here is the full traceback for the error, caused by attempting to save a Question object from the admin site:
https://www.ppaste.org/EhhmjVBrv
Python Programming Language Facebook Group Code Share
Python Programming Language Facebook Group Code Share
It's possible that it has to do with the id property, which isnt defined in the model but which is added by some Django magic at some unknown point. I will experiment with that
Because your implementation of eq is wrong
It's saying the attribute other of an object self (i.e. the current model instance) doesn't exist. And it doesn't
Because other isn't an attribute, it's an argument passed to the __eq__ function
So it should be self.id == other
However, you should compare against the id, so self.id == other.id
And then, you end up with a simplified version of what Django already does by default for equality comparison, so this is redundant.
By default Django compares the values of the primary keys of models to determine equality.
@proper hinge thank you for this response, I'm going to see if I can improve it. There are probably a lot of things that Django does that Im just not educated on yet.
Wow I feel stupid about the implementation of __eq__ thing
That was just an error I should have seen
So, the reason I added this at all is because I wanted to use sorted() on my objects and thought it was a good time to play with adding dunder methods and experiment.
How would you sort objects then if not by this way I tried to do?
I still get AttributeError: 'NoneType' object has no attribute 'id' but I know why that is. Its probably because it doesnt have the id yet like I was saying before. But, it does seem to be sorting my questions without sorted() and without the dunder methods.
the thing is... at one point is wasnt. Thats why I did this. I cant easily replicate what it was that caused that because it wasnt recent. So theres no proof that Im not imagining it :P
Either way thanks
anyone has done django with react?
Hi when trying to update the row of a user object I am getting this:
AttributeError: can't set attribute```
This is kinda my update func
def updatehandler(User):
print('[Update Handler] {}'.format(User.username))
userobject = session.query(users).filter_by(username=str(User.username)).first()
print(userobject)
userobject.username = User.username
userobject.password = User.password
userobject.email = User.email
userobject.firstname = User.firstname
userobject.lastname = User.lastname
userobject.birthdate = User.birthdate
userobject.about = User.about
session.commit()
return
Hi
I need urgent help
I want to calulate time between two different api calls for a user
How can I do that
using epochs
@app.route('/getdate', methods=['POST'])
def add_date():
req = request.json
#print(req)
client_time = int(req)
timenow = int(time.now().timestamp())
res = make_response("")
if timenow - client_time >= 84600:
res.set_cookie('disabled', disabledjwt('false'))
else:
res.set_cookie('disabled', disabledjwt('true'))
res.headers['location'] = url_for('lolcreator')
return res, 302
this checks whether one day exactly has passed
1 epoch is 1 second
Okay thanks
np
Hey @rustic pebble can you explain how this works
I have two APIs
One where uses selects a particular form to fill
And then he hits submit
So I want to record time between these two API calls
On a website right?
Yeah
Well you need to send a POST request with the data you want, for your case datetime, using javascript
Id suggest using fetchapi
Well
I have all these APIs already working
But the thing is
I want to know how long user takes to fill the form
So say I start a timer
When he hits the form url
Now I have to stop it
When the same user hits submit
I have a postgress DB
I will update the time difference in the data base
I would do this with the following way:
1) When page is loaded start js timer
2) when button submit is pressed stop timer
3) pass the timer value as a parameter on your apicall
You mean
I should do this from front end
And then send it to backend to update the database
But I can't do that
It has to be handled through backend
Why not?
You would have to send a seperate request to start a server-sided timer then
and stop it when the apicall from the submit gets returned
@rotund crescent if u are in flask flask-moment could suit you , im bit late didnt read whole disc. tho
Flask moment
Okay
Will try that
@rustic pebble I can't because I don't have access to frontend
Also
How are you building the website then haha
It's REST API
Hmm
You have a function fromNow() in flask moment i guess u could use it to calculate times or something hm
I guess you could either that ^^
If your code is async you could add a timer when the page gets loaded
Okay
And I have end the same timer
For same user
When he clicks submit
But how ?
I would like to measure time a user needs to take a decision (or just pressing the "submit" button in this case). In the python itself I normally measure the time of code with
start_time = time.cl...
i jsut gave it a quick google
dunno if it helps
@native tide Lemme check da
Is using relative paths in flask a norm or just personal pref ?
I am not sure exactly how to do this but you would need to create an async function say :
async def timer():
time = 0
while True:
await asyncio.sleep(1)
time += time
return time
--WHEN USER OPENS FORM PAGE--
@app.route('/form')
def things():
task = create_task(timer())
#your stuff here
---WHEN USER CLICKS SUBMIT---
#ur functions
task.cancel()
Or you could set a cookie that contains the onload epochs
and then grab that cookie again on user submit
The cookie thing works
And compare epochs
Just make sure you encrypt the cookie, I encrypt the cookies with JWT
Because if you want to use this data as case for something else users might try to change the cookie values
And it isn't actually encrypted, it is signed
Yea mb
This returns a signed key for example
def loginhandler(LogUser):
headers = {'alg': 'RS256'}
key = read_file('privateKey.pem')
objectuser = session.query(User).filter_by(username=LogUser.username).first()
print(objectuser)
starters = objectuser.firstname[:1] + objectuser.lastname[:1]
print(starters)
payload = {'username': str(LogUser.username), 'firstname':LogUser.firstname, 'lastname':LogUser.lastname,'starters':starters, 'aboutme': objectuser.about , 'iat': time.now()}
print(check_password_hash(objectuser.password, LogUser.password))
try:
if nobjectuser.username == LogUser.username and not(check_password_hash(objectuser.password, LogUser.password)):
print('Wrong credentials')
return None
else:
print('User {} has been found'.format(objectuser.username))
token = jwt.encode(headers, payload, key).decode('utf-8')
print(token)
return token
except:
print("Wrong credentials")
return None
You can see the content of the cookie by decoding with base64 the part before the dot
Cool thanks
Does anybody know why this updates all the rows instead of the one that is inside the where?
update = users.update().where(userobject.username == User.username).values(premium="WORKS")
Is it not SQL Alchemy ?
Wait
I have this kind of setup rn
userobject = session.query(users).filter_by(username=str(User.username)).first()
print(userobject)
print(User.username == userobject.username)
updated = users.update().where(userobject.username == User.username).values(premium="YESYESYES")
Ah just reverse the check
Okay
userobject = session.query(users).filter_by(username=str(User.username)).first()
print(userobject)
print(User.username == userobject.username)
updated = users.update().where(User.username == userobject.username).values(premium="YESYESYES")
I am sorry what I said was illogical
But it shouldnt matter since:
print(a==b) print(b==a)
@rustic pebble Typically, yes, but not strictly speaking necessarily so in Python
I got it
rows_changed = User.query.filter_by(role='admin').update(dict(permission='add_user')) db.session.commit()
Translate that to raw SQL, you're doing UPDATE whatever VALUES whatever WHERE true;
hmm
Or maybe I got it wrong I've never played with SQLAlchemy, but this seems to be the case
@rustic pebble use the code I sent
Btw I asked you to print str(User.username)
@bleak bobcat is right you should close the session after each update and update only for single session
Just to be sure, do a print(str(updated)) you'll get the actual SQL query
sec
@rotund crescent what u sent me doesnt work
UPDATE users SET premium=%s WHERE true
thats the response
god damn
:p
Found it
updated = users.update().where(users.c.username == User.username).values(premium="wofefeafearks")
Does Flask deal well with multiple requests at once?
__name__ right?
im following instructions in a book
"running your flask webapp for the first time"
i just copied the code as in the book .. but when i try running it from cmd a get this error
I mean, you wrote app = Flask(__name__) right?
yes
from flask import Flask
app = Flask(name)
@app.route('/')
def hello() -> str:
return 'Hello world from Flask!'
app.run()
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!')
Yes
Nice!
the book should highlight that
In most case, when you see underscores around a name, they are two of them
got it thanks !
They are called dunders, for double underscores
Can someone explain to me how decorators in flask work in our benefit for auth?
I am not rly familiar with decorators at all tbh
Decorators are just a fancy way of passing a function as a parameter
And in flask they usually permit access if you are let's say not an admin or not authenticated
My question can be a little strange. Its about web-development, but not back-end such as django, flask, etc, but about front-end. I red an article (https://www.quora.com/Is-it-possible-to-use-Python-for-web-development-without-involving-JavaScript) that tells about how we can use python is client-side web development. Basically, considering that browser cant compile python, the article tells that we can create py script, then we it will be converted in js. Now i would ask you, if anyone has ever used some of these tecnology, how are them...?
if its worth, i have just an idea to create some built-in library
That's one of the worst screenshot I saw in a while :D
Sorry these are from my phone. Wait
There are a few libraries that let python run in browser they are super duper finiky and hard to work with
Such as pyodide and pyjs
I would wait few years so wasm gains some traction
Tbh, that sort of tech really scares me
Now it is from desktop
Yes, docs are daunting akarys
Because you don't actually run the code, you compile it to another language
You just shoot you in the foot
Pyodide uses some kind of magic to somehow run python in browser iirc
Actually no, it's transpiled
Ah, it isn't the 27Mo interpreter?
My bad
Ah okay
I'm waiting for that wasm to catch up
So no one is good...
I know it will be few years but when we get it to run properly it will be something else
And brython?
@toxic marten i know they are bad, noone has made proper implementation because quite frankly it's almost impossible
Then js is only way
Sad story
Are there any good resources on making a django app look not so plain html? I've been looking at soething like Tailwind or Bulma
Thanks @vagrant adder
@daring pecan what do you think of bootstrap?
@daring pecan Learn CSS
and html5
One does not need bootstrap or any of those big things, just learn how it works, you can make a lot look very good with very little
What would be faster, checking the response code if its equal to 200
or checking if the string is not in the response content?
Need help as I am looking to maximize performance
A number comparison is always faster
@vagrant adder Why did you say that it is hard work with (about python in client side programming)? I had never used it, so i dont know why๐ ๐
I just tried to watch some video on yt, it seems not very difficult at basic programming, also the dom manipulation seems quite easy. I would just only to understand
Is there a way I can add spacing to headers:
for example:
<h2>Hello World</h2>
this ^^ returns the same as
<h2>Hello World</h2>
Two headers inline do you mean?
No
The things I typed above both give
Hello World
instead of
Hello World and Hello World
I found it
this gives u 2 spaces
so
im thiking to create two headers, one with text-align: left, and the other one with text-align: right. But u want to use just only one header
Or you can create something like that
yup
<h1>Hello <span>world</span></h1>
h1 is full width
and span has margin right set to 0
try it
What have u used?
If u want to use bootstrap, u can do something like that with flex
<div class="d-flex justify-content-between">
<h1>Hello</h1>
<h1>world</h1>
</div>
Hello, is anyone here familiar with Django Channels?
I'm using Django Channels 2.0 and having some issues
does anyone here have any experience with webscraping?
I have everything set up, and everything works as intended until I get to database extractions
@odd yarrow sure
Im trying to download some files off a website but im having a little trouble ๐
I'm no expert, so I'll let them help you out. But when I'm doing webscraping I usually use beautiful soup. And if I can't do it with that, I'll use Selenium.
Im using beautiful soup
Between beautiful soup and Selenium you should be able to scrape most sites
its just that i dont know what im doing haha
is it okay if i send u some pics of what is going on? @dull solar
If none of the experts will chime in, then sure I'll take a look
Hi is there any way I can make the logo centered, because currently I am just making it centered with margin
Are there any web scraping experts that could help me out
@odd yarrow what do you want to do
im trying to download files off a site and into my local
yes
So I don't really know if if this isn't 100% python related. But I'm out of ideas.
I'm trying to launch my Flask App on my VPS, using Gunicorn & Nginx. So my site runs. But if I try to log-in for example, it doesn't show up in the logs that a POST request has been done. Because I get redirect to my home page, but it doesn't log me in.
And sometimes if I stop my gunicorn, it will show up in the logs that i've logged in.
I am trying to import mainfirst.js onto an HTML page. I have tried both doing the following:
<script src="../../../static/assets/js/main.js"></script>
<script type="text/javascript" src="{{ url_for('static',filename='assets/js/mainfirst.js') }}"></script>
I am getting
Cannot resolve file mainfirst.js but it actually exists as per image:
hello
when i specify the font in my css
and launch the website
the font is what it is suppose to be on google
but when i open my website in edge it is not there
it turns into a different font
how do i fix this?
i imported the fonts from google
@rustic pebble about centering use margin: 0 auto;
@native tide can you share some snippet of code?
@toxic marten thanks
@native tide ๐
Any idea about my other issue?
which one
They are the same
I am trying to import
mainfirst.jsonto anHTMLpage. I have tried both doing the following:
<script src="../../../static/assets/js/main.js"></script>
<script type="text/javascript" src="{{ url_for('static',filename='assets/js/mainfirst.js') }}"></script>I am getting
Cannot resolve file
mainfirst.jsbut it actually exists as per image:
@rustic pebble about that one?
Yup
Are you sure about relative path?
i never used jinja2 before lol
It is weird :/
Like the file gets loaded according to the console as it returns 200 but I cant access anything inside it
but wait, i suppose static is the path, and filename is the name of file, so there will be a concatenation to get full path
Yup
and i cant help you cause im pretty new in backend ๐ข
Ooh
im learning the theory concept about back-end. Then i will start with django/flask. Which one do you recomend to start with at first?
I am making a super complex website and I just cant get it to load that particular file
Flask has way less overhead
Go with it
More simple i red, true?
Flask? Yes it is
Which tutorial/documentation have u used to learn it?
I am making my website in flask rn
Nothing, I just dove into the hard stuff
It is so simple you will learning by implementing what you have in mind
Tuts and docs are good directors but canโt actually help you get started on a project
Btw here is a backend diagram
This can help you understand what you need to@learn for backend
Interesting there also C#. I used it a little for some school project
But i love python, so first flask, and then django๐
thanks
Well headless webapps are the future so its good looking into WPF
this should have to do with web dev
do any of you know how to work with adsense?
google adsense?
Not rly. Dont use ads though
It makes your website look money hungry
I donโt know the context of the website you are referring to, but freemium is a good business model
i that's what i thought about too it makes your website money hungry๐
what is freemium
i see
Depends on context
in a portolio website i don't really think
a website like udemy you can apply the freemium model
ah!
@toxic marten try with miguels flask mega tutorial
Its up on google , it was little bit too much for me in begging i know people hate udemy but i bought one course for 10 $ basics of flask or something it really served me well as i didnt have any clue whats going on so eh... But yeah i think miguel has a book , web development in flask second edition , its more begginer friendly than his free tutorial i think . There was just too much text for me once i saw the framework for first time , but doesnt mean it wont work for you. Good luck either way
for some reason my image doesn't show up when i launch my website to the heroku server
I have been doing a lot of work with django-s3-storage, it works well now that the legacy Python has been updated.
@native tide
What are you using, django-whitenoise ?
flask
Ohhh.
I use Heroku as well, and whitenoise is the default package for static files. How does Heroku accommodate Flask application static files ?
display: inline-block; vertical-align: top; OR display: flex;
[Django]
So would one set a template variable depending if it is prod or not ?
In my base template, I'd like to put something like:
{% if test_env %}
<test-env-banner/>
{% elif prod_env %}
<beta-env-banner>
{% elif demo_env %}
<demo-env-banner>
{% endif %}
[EDIT] Found help here: https://stackoverflow.com/questions/433162/can-i-access-constants-in-settings-py-from-templates-in-django
Hello. I am in desperate need of some Django deployment help. I am having issues getting easyapache 4 to use python 3.6 over 2.7. The server trys to load the wsgi.py file, has various import errors. It also does not seem to be using the venv i have my WSGIDaemonProcess setting. This could seem to be an easy matter but to complicate things, this is on a BlueHost CentOs/CPanel VPS which has made a lot of simple things tricky. Sorry if this is loaded but I am new to all of this and it seems like I do one thing right then 5 others break.
I'm also new to this kind of things and that's why I choose to deploy on Heroku, it handles that kind of stuff for you
It might be suitable depending your project
Yeah I wish I was able too but its for a client with an existing server ๐ฆ
Ah, then it's not an option. I can't help you then ๐
Thanks tho I wish I could help with yours but its honestly something I would like to know lol
Its up on google , it was little bit too much for me in begging i know people hate udemy but i bought one course for 10 $ basics of flask or something it really served me well as i didnt have any clue whats going on so eh... But yeah i think miguel has a book , web development in flask second edition , its more begginer friendly than his free tutorial i think . There was just too much text for me once i saw the framework for first time , but doesnt mean it wont work for you. Good luck either way
@native tide thank you. Ive just bought it on amazon
Do you say "g unicorn" or "gun i corn"
I think its supposed to be green unicorn? I say gun, as in a firearm, gunicorn
g u n i c o r n
Goon icorn
Weird, I say u w s g i
Guhnicorne
I also learned that wsgi is "whiskey" today
i pronounce each letter of SQL when people call it "sequel" around me
i never know what to say
It was originally called "structured English query language" so sequel made more sense
At some point we have to stop letting programmers name programs. There needs to be a committee or something.
but yeah, I also say S-Q-L no matter what people say around me
Sequel is a good name though
Yeah, Im not mad about the name
Its just that many years elapsed where I only saw the name in print.
And its just how I think of it.
I did my titles like this <title>Blog | {% block title %}{% endblock %}</title> in my base.html template
I should have just done Blog | {{ title }} and pass in context through the view.
Because its ultimately similar to type it as a block in every template, but its more typing at the end of the day
Which would you prefer?
I kind of dont want to redo it now that its done but I think its better to pass a title as context variable
Not sure i understand what you meant, but isn't title in a separate file like you did is better ?
So if you ever need to change, you do it once, instead of changing every view?
^^
Well, in each view there is context title and main title. Both work the same...
But in one, you specify the page title on a template's title block. The other way, you pass a title variable to the view. It's the same thing but different.
It's what causes it to say "about" on the about page.
Tbh, I am not using the child - parent system in jinja
I am going the old way with includes
therefore, I'd use a template variable
What you are asking is very opinion based IMHO ๐
ah, I use includes too on my base but I also have children. Either way you organize it s a lot easier than the way I did it before this which is page by page
For sure.
You're right
If it does not cause any issues,then do what feels right for you
yeah both are the same thing. It just depends on which file you'd rather have the info on.
Hi, what will be load faster on the same servers.. wordpress website/Flask/Django?
the website I want to do, can be build in all of the options.. but I want to make the fastest website as I can
I have build alot of websites in wordpress always had a bad of loading results..
and Now I just started to get into Flask and Django and feels ready to build one in these ways
Out of the box without any optimization/cache setup etc... Flask would probably be the fastest
Does anyone knows how do I get the user object using the token with knox + DRF? I'm trying to authenticate a endpoint with js window.open using cookies
Flask is the fastest out of those you pointed out just because it doesn't have almost no overhead @pliant falcon
However, most Python sites cost more than a PHP host, that is something to consider
My web costs me 3โฌ/month for hosting and 7โฌ/year for the domain, serving a blog with static html
Python hosting can also get expensive if someone is causing server stress via your script since many charge per cpu cycles
if you want a pythonic web but without running python on the web host, take a look at static site generators such as lektor or jekyll (although Ruby)
static sites have many security advantages
@pliant falcon
Thanks for the answers, actually if I create an contact form in flask is it means the website isnโt static?
No, because there is dynamic code on the webserver. Static means there are only html files
Yes
It has advantages and some disadvantages
I am using jekyll and one disadvantage was, that search was unavailable
I've solved this with a rest-like endpoint that can search and added the functionality via javascript
The PHP script for that was like 20 lines: https://rest.tuxstash.de/search.php?search-pattern=icinga
Doing Flaks on your own web is no simple task and you need to stay atop on things, but I don't want to discourage you, just giving options you may not be aware of
ahh so actually if I dont use dynamic code why should I use python in any case.. HTML and css does everything else
am I wrong
You can use python to generate the html
Jekyll takes markdown and turns it into blog posts
ahh
cool
For example do you know github pages?
That uses jekyll
I've built that on my own on my RasPi
so my current project is to build my an agency one page.. but with contact form
wow this website that you sent me so fast
For example do you know github pages?
@tired root Yes
which one?
both
That is the power of pure html. NO delay for script execution
so this Lektor and Jekyll are a differents ways to build websites with python?
Jekyll is Ruby
But yes, it is a different way to build your web. It generates static data.
However, for a one page with a contact form, I'd suggest doing it in pure html and using php for the contact form
It should be a simple script
It is the fastest and easiest way and I feel shooting with Flask onto a contact form is a bit overkil
considering maintenance and upkeep cost
I actually really good with HTML and bootstrap.. the only thing I need is to build an contact form
do it in php
shouldn't be more than 10-20 lines
$from = "someonelse@example.com";
$headers = "From:" . $from;
echo mail ("borutflis1@gmail.com" ,"testmailfunction" , "Oj",$headers);
I have trouble sending email in PHP. I get an error: SMTP server
and it's just for using cheaper servers? or it's diff in performance aswell?
Considering a one page is one big file of html, performance isn't really a consideration
keep it small, minify it
regarding the php script, that executes in less than a second
I'd be more worried about bootstrap size increasing load times tbh
look for something smaller to create the page
ALso don't forget the htaccess caching instructions
those save a lot of loading time
Example from my homepage: ```apache
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 30 minutes"
ExpiresByType text/html "access plus 1 hour"
ExpiresByType text/plain "access plus 1 hour"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
</IfModule>```
And yes, php hosts are very cheap
what is this?
Apache instructions for caching
wow you giving me gold info that I didn't know
in wordpres for every thing I installed a plugin XD
Yeah.
And yes, most php hosts are cheaper than Python hosts, as I said.
For example python anywhere charges per cpu cycles
A webpackage with php shouldn't cost more than 3-4 bucks/month
including traffic
Yes.. it's alot cheaper
so you say if I wanted to create alot of pages it was better to use flask or maybe flask and then one of the generaters.. but for this purpose it better to build pure html with php just for the form
the thing is that I will use bootstrap anyway
If you have a large site that requires a lot of optimization and you expect a lot of in-/output, Flask is definitely the better way. For a simple one-page with a contact form, I'd say it is overkill and increases maintenance needs needlessly.
Also building time
You can do that php script with the SO post I've linked and the rest in 1-2 days
A Flask site requires definitely more effort
bootstrap makes it easy for me to handke responsivity and designing beuatiful ui
thanks man
no problemo
@tired root what do you mean by CPU cycles?
It is an instruction executed by the CPU
To simplify things, they just charge based on CPU usage
Which is the default margin for dl dt dd element in bootstrap?
Is there a way I can set a local css
I am trying to create a layer but the css of the layer is overlapping with the one of the main body
it calls the function
What are you trying to achieve?
You could that client-sided with js
But basically
I guess you need a way to receive the request
You want live updates without any reload
?
Can you show me the render_template function you have?
Where do you want to display
The rate
But that isnt displaying it
it is an attribute
But I will lay it down for you here:
Basically when the template gets rendered you can pass in global variables.
Say you have this backend setup:
@app.route('/')
def home():
rates = get_currency_exchange_rates()
return render_template('home.html', rates=rates)
<a href="#" class="dropdown-item" role="presentation" exchange-rate="{{currency.EUR}}" value="EUR">
<span id="currency-symbol" style="padding-right: 4px;">{{rate}}โฌ</span><span id="currency-name">Euro</span>
</a>
On page load
it will render the current rates value to the span
Unfortunately
or you can add a common id to all websites
create a rates.js file and do the following:
say id is currentrates
function loadRates(rates){
let rates = {{rates}};
domspan = document.getElementById('currentrates');
domspan.innerHTML = rates;
}
Also if you want to force a reload
hmm
I am not actually sure how you can make the server and the client refresh at the same time
You could just add a timer in server to re-render the template every 1 hour. And then set a seperate timer on the client to refresh it every one hour as well
Basically you would need this:
def reloadtimer():
while True:
home()
time.sleep(3600)
3600 is one hour in seconds
๐
Is there anybody who has set-up PayPal on Flask before? I need help!
Im working with bootstrap, but i have a problem. In mobile page there is a white gap on right side. How to fix?
Is there anybody who has set-up PayPal on Flask before? I need help!
@rustic pebble sorry ive no idea๐ฆ
God damn it man
I am so close to making it work
but I just cant set up the backend because paypal hasnt released a flask or at least django related sdk
I will copy paste and adjust
@toxic marten I am not sure what can cause that
I know bootstrap but onlyto help myself :/
@rustic pebble im pre-intermediate. im mastering it
Are you good on backend tho?
however. i red on stackoverflow that it can be caused by row nesting without creating .col directly child of rows. But that not my case. I think thats the title that is too big
Are you good on backend tho?
@rustic pebble No, i started this morning with flask with basics lol
Ooh
I am good with backend, medium with frontend
But there are some things like PayPal sdk
that gives me PTSD after finally setting them up
this can help you? https://pythonprogramming.net/paypal-flask-tutorial/
Python Programming tutorials from beginner to advanced on a massive variety of topics. All video and text tutorials are free.
The problem is that is not using the paypal sdk
Ah. i really have no idea
At least I got it to connect
So I got it to make a test transaction
I believe I am in a good path rn
@rustic pebble you can use a context processor if you need a variable on every single page
@dry pawn Thanks I will use that.
I overlooked a couple of things. How well is my Flask backend gonna handle a handful of users at the same time? Do I need to do some extra configuration?
I don't know flask but that kind of feature is builtin, it's a given that you' ll have multiple users at the same time.
I am setting the price for the paypal renderer on the client by making a request on my server and getting the return value
Is there a way I can make that more secured
Flask is a compiled version of CPython
It can multitask @native tide
Ok great
๐
For Django models db, how to set default rows? I want this fetch data from https://pokeapi.co , format it and insert to db while creating table.
An open RESTful API for Pokรฉmon data
I'm not sure I understand what you want/need, can you elaborate ?
@valid cypress you can set the default kward of your key
It act as a fallback if no value is provided for that key
But he's asking for rows, not columns/attributes, that's why I'm wondering what he really wants
I mean, a row is technically a model key
But this have 800+ entries
You have 800 entries in your model?
PokeAPI have 800+ entries, that I want to my db
Wait, you want to copy the entire PokรฉAPI db to your own database?
I am sure you can do what you want witj an api
One endpoint
So you want to copy their database?
Basically, but in different format
You'll have some hard time copying a full database, mainly because of rate limits
But what you can do, is have a lazy database
You don't copy anything until the user request a specific data, then you ask the API and store it into your own db
But I don't see how this is related to your question
I'm making Pokemon bot with Django admin panel. I want get things to DB only in first setup/start.
I mean, you are really going to spam the API with 800 requests at startup?
It seems kind of unreasonable
Only first startup
It is still unreasonable
They have a database, why would you want to copy it entirely
You should also take a look if they have any github, maybe you can find a static file containing all the data here
It may be unreasonable but their rate limit is 100 API requests per IP address per minute so he could do it over the span of 10min
Then again if you look at their doc they have a python 3 wrapper with auto-caching : https://github.com/PokeAPI/pokebase which might be a lot more reasonable and easy to use
hey guys
that https://github.com/django-erp/django-erp is working? anybody knows anything about it?
i need to modify it
@valid cypress why arent u just making on user command requests
Due then I'll have to do 5 request per command use.
First: Pokemon Species fetch
Second: Pokemon fetch
Third: Item fetch
Forth: Ability fetch
Fifth: Nature fetch
But I can combine them to one request with my API
You should do 5 requests per user request and use caching
Or it would takes way too much time to sync
I would make a lazy db
Easiest and best
You only get what you need and it gets added to sql as well
In DTE, sometimes I see {% some_var|this %} and I'm not really sure what to call that. I've seen pluralize which seems to know if a numeric variable should have a word with an 's' or not. I've also seen crispy which refers to django-crispy-forms and sort of applies automatic CSS to a form object.
TLDR what is the word for what these are?
filter
It's a filter
Some are built-in, some come from libraries (like crispy), and you can also create your own
Is there anyway I can add a seperation line between Full Name - Email and Username - Password
Sorry for overlapping ur request @native tide
@rustic pebble do you mean an <hr>?
@rustic pebble You mean a line break?
I mean a horizontal line
that works as a seperator
yea an hr
I forgot about that
omg
Ok. Do you forgot about hr tag?