#web-development

2 messages ยท Page 43 of 1

bold mortar
#

thanks @rigid laurel

rigid laurel
#

@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

heady thorn
#

Thanks @rigid laurel awsome. So flask +fastapi +Vue is ok?

rigid laurel
#

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?

heady thorn
#

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 :)

rigid laurel
#

Yeah, both Flask and FastAPI can do rest-APIs, just FastAPI is a bit nicer for it IMO

heady thorn
#

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.

rigid laurel
#

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

heady thorn
#

Nice. I might check out jupyter notebooks too I hear also good

#

Right thanks Charlie. And thanks for the warm welcome to the community ๐Ÿ˜

rigid laurel
#

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

heady thorn
#

๐Ÿคž๐Ÿ‘๐ŸคŸ

rustic pebble
#

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?

broken oasis
#

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.

quasi ridge
#

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

broken oasis
#

@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

quasi ridge
#

sorry, I have no idea what "imread" is or how it works

broken oasis
#

in this case it is the first line of my ocr function

quasi ridge
#

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

broken oasis
#

So i guess i will stick to saving then deleting it after ocr...

quasi ridge
#

you might even use the "tempfile" library

broken oasis
#

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

quasi ridge
#

no idea

#

dunno what "aws elb" is

broken oasis
#

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

quasi ridge
#

well, I still don't know why you're seeing that difference.

rustic pebble
#

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

broken oasis
#

@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

quasi ridge
#

gรผd

native tide
#

Hi.

#

I'm trying to execute a script in PHP

#

Then return a variable to PHP

#

Is it possible?

tired root
#

This is a python server

#

but yes it is possible

#

@native tide

true orbit
#

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>

quartz lily
#

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

tired root
#

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

quartz lily
#

well

tired root
#

Just to let you know, I fully concur with what has been said on SO. Use a database

quartz lily
#

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

tired root
#

so?

#

that is what databases are there for

#

Also, with caching you can minimize all that

quartz lily
#

there will be over 10k reads at once at a tome

#

time

#

its gonna be so much

tired root
#

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?

quartz lily
#

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

tired root
#

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

quartz lily
#

yeah so basically each time someone loads the home page, it would need to make a check to the database

tired root
#

yes

quartz lily
#

isnt that a lot of reading

tired root
#

no

#

it isnt

quartz lily
#

it could be 10k per second actually.

tired root
#

What kind of setup do you have?

quartz lily
#

for a span of 10-15 min

#

some pythonanywhere server, I can share the specs in 5 minutes

tired root
#

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

pseudo nacelle
#

SO is brutal

#

-3

quartz lily
#

lmao yea

#

and im thinking to just use a file rn, and work out the db later

rustic pebble
#

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

quartz lily
#

jquery

#

make a request to a route which does all the necessary computations

#

or ajax

#

and then from your route, return the data

rustic pebble
#

hmm

#

can u give me an example

quartz lily
#

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

rustic pebble
#

hm ok

quartz lily
#

if you don't know how to use flask routes i would suggest looking into those first

#

cause those are the basics

rustic pebble
#

I know how to use flask routes

#

I just dont know how to use js

#

๐Ÿ˜„

quartz lily
#

google jquery and learn about it

#

same with ajax

#

it's pretty simple

rustic pebble
#

will this return the value of the element?

#

var number = document.getElementById('clicks').value

#

say the value was '500'

quartz lily
#

Yeah

#

That works

#

depends on what element clicks is though

#

and thats more JS, it's much easier to use jquery

rustic pebble
#
                            function submit(){
                              const http = new XMLHttpRequest();
                              https.open("POST", "/lolcreator");
                              https.send;
                            }
#

This should work

#

but it doesnt right?

quartz lily
#

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

rustic pebble
#

i am doing it for test

tired root
#

If you need bidirectional communication, use a websocket, not ajax requests

#

@rustic pebble

rustic pebble
#

I need this:
Send request to a flask path -> flask path returns a string -> alert(string)

tired root
#

again, use websockets, then your frontend and your backend can talk to each other

#

without reloading

rustic pebble
#

I am not rly sure how to do that either, but I will try

tired root
#

Or maybe rethink if you really need it without reload

#

another option is a rest api with the ability to POST

rustic pebble
#

I really need it without a reload

tired root
#

why?

rustic pebble
#

for ux

tired root
#

if you explain what you do, maybe one can help you

rustic pebble
#

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

umbral palm
#

@rustic pebble Use ajax maybe?

rigid laurel
#

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

full panther
#

anyone knows how can i send a file to my flask server with requests?

rigid laurel
#

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"]

full panther
#

oh thanks :)
i managed to send the file but when i recieve the file it doesnt recieve it in binary

rigid laurel
#

what mode are you using to read the file?

#

as in 'r' or 'rb'?

full panther
#

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

rustic pebble
#

@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

rigid laurel
#

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?

rustic pebble
#

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

rigid laurel
#

None of that is very difficult to do with a little JS

#

But explaining it isn't necessarily easy

#

hm

rustic pebble
#

I am still in the process of learning js

#

I try to add almost everything in python

rigid laurel
#

yeah, its the kinda thing thats easy once you know it, but very alien if you don't know it

rustic pebble
#

not really. I know c#

#

so it is not very strange to me

#

it just misses the linq part which i am grateful for

rigid laurel
#

a high level overview is that you want to:

  1. use the fetch API to make the post request to flask with the new settings
  2. In flask respond to that with a json
  3. Using the fetch API, when you get a response, update the html content of what you want to change
rustic pebble
#

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+'&amp;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

rigid laurel
#

You don't want to be using xmlhttprequest

rustic pebble
#

and works just fine

#

hmm

rigid laurel
#

use the fetch api or use jquery

rustic pebble
#

So I have been told,

rigid laurel
#

I'd definitely reccomend the fetch API.

But with what you have, what is the problem

#

updating the content on the page?

rustic pebble
#

Yup

#

I am using a 302 on flask

#

once content is done being processed

rigid laurel
#

what are you returning with flask? A json or html?

rustic pebble
#

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

rigid laurel
#

From the client side, you need to essentially manually update only the values that you want to update

rustic pebble
#

For example these left are the starters of a users first and last name

#

along with the username

rigid laurel
#

so you'd want to return a json instead of the template

#

return dict(data1=data1, data2=data2...)

rustic pebble
#

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

rigid laurel
#

then on the js side you select the elements you want to update

#

and change their values

rustic pebble
#

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

rigid laurel
#

alert(http.responseText); --> let my_response = JSON.parse(http.responseText)

#

and then you have a JS object

rustic pebble
#

what does let do?

rigid laurel
#

same as var

#

but scopes to the current block instead of the current function

rustic pebble
#

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?

rigid laurel
#

yeah, that looks right

#

ish

#

its been a while since I've used jquery

#

I've mostly used the fetch api recently

rustic pebble
#

I have never used fetch api beforehand

rigid laurel
#

its very promisey, but its pretty good

rustic pebble
#

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

rigid laurel
#

yeah, that looks right

#

does it work?

rustic pebble
#

let me try it

#

havent used it, I was waiting for ur response

#

I am getting this

#

Although I am using it

rigid laurel
#
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

rustic pebble
#

That being async wont mess with the rest of the js I have on the website right?

rigid laurel
#

I think it should

#

not 100%

rustic pebble
#

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

rigid laurel
#
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
  });
rustic pebble
#

its calling the function from otuside

#

haha

#

yy

#

:/

rigid laurel
#

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

rustic pebble
#

Ok I fixed the request

#

it makes it

#

Method not allowed is okay, I havent configured it

rigid laurel
#

Yeah, thats a problem on the flask side of things

rustic pebble
#

I know

#

but the syntax error? :/

rigid laurel
#

thats because you aren't returning a json from the flask

#

I'm pretty sure

#

its just getting the default flask error

rustic pebble
#

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

rigid laurel
#

which is a html 403 or whatever

rustic pebble
#

return {'Success'}

#

this should return a json right?

umbral palm
#

its not valid json

rigid laurel
#

yeah, it should

#

oh actually

#

won't like that

#

it'll think its a set

rustic pebble
#

dict

rigid laurel
#

no, that will think its a set

rustic pebble
#

dict('Success':'True')

rigid laurel
#

that will work yeah

rustic pebble
#

or not

#

it doesnt work like that apparently

rigid laurel
#

{'succes':True} or dict(success=True)

rustic pebble
#

dict('Success')

rigid laurel
#

needs to be an equals if you use the dict() method or a :; if you do it with the literal

rustic pebble
#

What if I do

#
    response = {'Response':'Success'}
    return response
rigid laurel
#

that should work yeah

rustic pebble
#

If I wanted to print the response onto console

#

I would do console.log(response.json());

rigid laurel
#
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

rustic pebble
#

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();
rigid laurel
#

then when you call the function, you need to do postData(url, what_youre_sending_to_flask).then((data) => { console.log(data)})

rustic pebble
#

ookk

#

let me try

#

๐Ÿ™‚

rigid laurel
#

There you go, now you just need to replace that with some JS to update the content

rustic pebble
#

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?

rigid laurel
#

well, you'd just be calling it inside the then() so you should be fine to call non async stuff there I think

rustic pebble
#

Soo, I will have to do .then((data) => function1(), function2(), etc)

#

to call the functions

rigid laurel
#

yeah

#

pretty much

rustic pebble
#

but data is in dict, if I wanted to display only username I would do:
.then((data) => function1(data['username'])

#

?

rigid laurel
#

you could do that, but its just a js object, so you'd probably want to do data.username

rustic pebble
#

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

rigid laurel
#

You already have the table, and you just want co change all values in a column?

rustic pebble
#

I want to add values depending on reponse count

#

so if 5 was received it would create 5 rows

rigid laurel
#

ah, gotcha

rustic pebble
#

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)

limber laurel
#

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

restive kindle
#

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

rustic pebble
#

I am getting : $.notify is not a function

#

But I have included both jquery and bootstrap-notify beforehand

haughty saffron
#

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

native tide
#

Little Question is it possible to give a php variabel a value with a Python command

amber furnace
#

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

haughty saffron
#

im aware

#

its a placeholder

#

and i figured it out

amber furnace
#

๐Ÿ‘

woeful parrot
native tide
#

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

#

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

proper hinge
#

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.

native tide
#

@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

native tide
#

anyone has done django with react?

rustic pebble
#

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
rotund crescent
#

Hi

#

I need urgent help

#

I want to calulate time between two different api calls for a user

#

How can I do that

rustic pebble
#

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

rotund crescent
#

Okay

#

So can I get different time for different logins

#

Using this

rustic pebble
#

you get different time yes

#

But that depends on how requests to the url are made

rotund crescent
#

Okay thanks

rustic pebble
#

np

rotund crescent
#

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

rustic pebble
#

On a website right?

rotund crescent
#

Yeah

rustic pebble
#

Well you need to send a POST request with the data you want, for your case datetime, using javascript

#

Id suggest using fetchapi

rotund crescent
#

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

rustic pebble
#

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

rotund crescent
#

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

rustic pebble
#

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

native tide
#

@rotund crescent if u are in flask flask-moment could suit you , im bit late didnt read whole disc. tho

rotund crescent
#

Flask moment

#

Okay

#

Will try that

#

@rustic pebble I can't because I don't have access to frontend

#

Also

rustic pebble
#

How are you building the website then haha

rotund crescent
#

It's REST API

rustic pebble
#

Hmm

rotund crescent
#

And The frontend and backend are two separate services

#

The guy is not available

native tide
#

You have a function fromNow() in flask moment i guess u could use it to calculate times or something hm

rustic pebble
#

I guess you could either that ^^

#

If your code is async you could add a timer when the page gets loaded

rotund crescent
#

Okay

#

And I have end the same timer

#

For same user

#

When he clicks submit

#

But how ?

native tide
#

i jsut gave it a quick google

#

dunno if it helps

rotund crescent
#

@native tide Lemme check da

native tide
#

Is using relative paths in flask a norm or just personal pref ?

rustic pebble
#

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

rotund crescent
#

The cookie thing works

rustic pebble
#

And compare epochs

rotund crescent
#

Yupp

#

Thnks @rustic pebble @native tide

rustic pebble
#

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

jagged lark
#

JWT isn't an encryption method

#

That's a token format

rustic pebble
#

You can use

#

jwt.encode

#

with public and privatekey

jagged lark
#

And it isn't actually encrypted, it is signed

rustic pebble
#

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
jagged lark
#

You can see the content of the cookie by decoding with base64 the part before the dot

rotund crescent
#

Cool thanks

rustic pebble
#

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")
rotund crescent
#

Use fitler instead of where

#

@rustic pebble

rustic pebble
#

Cant use it that when updating

rotund crescent
#

Is it not SQL Alchemy ?

rustic pebble
#

yup it is

#

But I am not querying

rotund crescent
#

Wait

rustic pebble
#

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")
rotund crescent
#

Ah just reverse the check

rustic pebble
#

let me try that

#

Again sameproblem

rotund crescent
#

Okay

rustic pebble
#
    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")
rotund crescent
#

I am sorry what I said was illogical

rustic pebble
#

But it shouldnt matter since:

print(a==b)
print(b==a)
#

It is the same

rotund crescent
#

Okay

#

Can you print the user name in console

rustic pebble
#

Yup

#

it works

patent cobalt
#

But it shouldnt matter since:

print(a==b)
print(b==a)

@rustic pebble Typically, yes, but not strictly speaking necessarily so in Python

rustic pebble
#

I got it

rotund crescent
#

rows_changed = User.query.filter_by(role='admin').update(dict(permission='add_user')) db.session.commit()

bleak bobcat
#

Translate that to raw SQL, you're doing UPDATE whatever VALUES whatever WHERE true;

rustic pebble
#

hmm

bleak bobcat
#

Or maybe I got it wrong I've never played with SQLAlchemy, but this seems to be the case

rotund crescent
#

@rustic pebble use the code I sent

rustic pebble
#

sec

#

User or session?

#

@rotund crescent

rotund crescent
#

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

bleak bobcat
#

Just to be sure, do a print(str(updated)) you'll get the actual SQL query

rustic pebble
#

sec

#

@rotund crescent what u sent me doesnt work

#

UPDATE users SET premium=%s WHERE true

#

thats the response

#

god damn

bleak bobcat
#

:p

rustic pebble
#

Found it

#

updated = users.update().where(users.c.username == User.username).values(premium="wofefeafearks")

fierce frost
#

Does Flask deal well with multiple requests at once?

lapis wedge
#

py -3 webapp.py
Traceback (most recent call last):
File "webapp.py", line 3, in <module>
app = Flask(name)
NameError: name 'name' is not defined

#

help

jagged lark
#

__name__ right?

lapis wedge
#

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

jagged lark
#

I mean, you wrote app = Flask(__name__) right?

lapis wedge
#

yes

jagged lark
#

With two underscores?

#

On each side

lapis wedge
#

from flask import Flask

app = Flask(name)

@app.route('/')
def hello() -> str:
return 'Hello world from Flask!'

app.run()

jagged lark
#

4 in total

#

!codeblock please use a codeblock

lavish prismBOT
#

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!')
lapis wedge
#

oh

#

two underscore from each side ?

#

lol ok lemme try

jagged lark
#

Yes

lapis wedge
#

yep. that was it ๐Ÿ™‚

#

thanks my bad @jagged lark

jagged lark
#

Nice!

lapis wedge
#

the book should highlight that

jagged lark
#

In most case, when you see underscores around a name, they are two of them

lapis wedge
#

got it thanks !

jagged lark
#

They are called dunders, for double underscores

lapis wedge
#

haha dunders!

#

thank u sir

rustic pebble
#

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

vagrant adder
#

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

toxic marten
#

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

jagged lark
#

That's one of the worst screenshot I saw in a while :D

toxic marten
#

Sorry these are from my phone. Wait

vagrant adder
#

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

jagged lark
#

Tbh, that sort of tech really scares me

toxic marten
vagrant adder
#

Yes, docs are daunting akarys

jagged lark
#

Because you don't actually run the code, you compile it to another language

#

You just shoot you in the foot

vagrant adder
#

Pyodide uses some kind of magic to somehow run python in browser iirc

#

Actually no, it's transpiled

jagged lark
#

Ah, it isn't the 27Mo interpreter?

vagrant adder
#

My bad

jagged lark
#

Ah okay

vagrant adder
#

I'm waiting for that wasm to catch up

toxic marten
#

So no one is good...

vagrant adder
#

I know it will be few years but when we get it to run properly it will be something else

toxic marten
#

And brython?

vagrant adder
#

@toxic marten i know they are bad, noone has made proper implementation because quite frankly it's almost impossible

toxic marten
#

So i must use js

#

No other possibilites

vagrant adder
#

Then js is only way

toxic marten
#

Sad story

daring pecan
#

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

rustic pebble
#

Thanks @vagrant adder

toxic marten
#

@daring pecan what do you think of bootstrap?

tired root
#

@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

native tide
#

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

tired root
#

A number comparison is always faster

toxic marten
#

@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

rustic pebble
#

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>
toxic marten
#

Two headers inline do you mean?

rustic pebble
#

No

#

The things I typed above both give
Hello World

#

instead of
Hello World and Hello World

#

I found it

#

&nbsp;&nbsp; this gives u 2 spaces

#

so

toxic marten
#

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

rustic pebble
#

yup

toxic marten
#

<h1>Hello <span>world</span></h1>

#

h1 is full width

#

and span has margin right set to 0

#

try it

rustic pebble
#

I am using custom styling

#

and it will ruin it

#

but what I sent works just fine

toxic marten
#

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>

rustic pebble
#

Oh okay

#

thanks

dull solar
#

Hello, is anyone here familiar with Django Channels?

#

I'm using Django Channels 2.0 and having some issues

odd yarrow
#

does anyone here have any experience with webscraping?

dull solar
#

I have everything set up, and everything works as intended until I get to database extractions

#

@odd yarrow sure

odd yarrow
#

Im trying to download some files off a website but im having a little trouble ๐Ÿ™‚

dull solar
#

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.

odd yarrow
#

Im using beautiful soup

dull solar
#

Between beautiful soup and Selenium you should be able to scrape most sites

odd yarrow
#

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

dull solar
#

If none of the experts will chime in, then sure I'll take a look

rustic pebble
#

Hi is there any way I can make the logo centered, because currently I am just making it centered with margin

odd yarrow
#

Are there any web scraping experts that could help me out

rustic pebble
#

@odd yarrow what do you want to do

odd yarrow
#

im trying to download files off a site and into my local

rustic pebble
#

sure

#

Are you sure it is allowed on their TOS?

odd yarrow
#

yes

hoary spruce
#

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.

rustic pebble
#

But I have added the js script to the html head

rustic pebble
#

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:

native tide
#

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?

native tide
#

i imported the fonts from google

toxic marten
#

@rustic pebble about centering use margin: 0 auto;

#

@native tide can you share some snippet of code?

rustic pebble
#

@toxic marten thanks

native tide
#

i got it

#

thanks anyway

#

i just forgot to import the fonts

toxic marten
#

@native tide ๐Ÿ‘

rustic pebble
#

Any idea about my other issue?

toxic marten
#

which one

rustic pebble
#

They are the same

toxic marten
#

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:
@rustic pebble about that one?

rustic pebble
#

Yup

toxic marten
#

Are you sure about relative path?

rustic pebble
#

Yup

#

I copy and pasted it

toxic marten
#

i never used jinja2 before lol

rustic pebble
#

It is weird :/

#

Like the file gets loaded according to the console as it returns 200 but I cant access anything inside it

toxic marten
#

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

rustic pebble
#

Yup

#

As I said it gets loaded but I cant access anything inside it

toxic marten
#

i dont know man

#

very strange

rustic pebble
#

Yup

toxic marten
#

and i cant help you cause im pretty new in backend ๐Ÿ˜ข

rustic pebble
#

Ooh

toxic marten
#

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?

rustic pebble
#

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

toxic marten
#

More simple i red, true?

rustic pebble
#

Flask? Yes it is

toxic marten
#

Which tutorial/documentation have u used to learn it?

rustic pebble
#

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

toxic marten
#

ok, so just do it

#

I mean no learning, start since the beginning with practice

rustic pebble
#

Btw here is a backend diagram

#

This can help you understand what you need to@learn for backend

toxic marten
#

Interesting there also C#. I used it a little for some school project

#

But i love python, so first flask, and then django๐Ÿ˜„

#

thanks

rustic pebble
#

Dont learn both

#

Its not pureC#. It uses the .NET framework

toxic marten
#

Yes. i prefer python

#

i used c# just for gui desktop project

rustic pebble
#

Well headless webapps are the future so its good looking into WPF

native tide
#

this should have to do with web dev

#

do any of you know how to work with adsense?

#

google adsense?

rustic pebble
#

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

native tide
#

i that's what i thought about too it makes your website money hungry๐Ÿ˜…

#

what is freemium

rustic pebble
native tide
#

i see

rustic pebble
#

An example

native tide
#

how to apply it to a website though?

#

i can see that happening in games

rustic pebble
#

Depends on context

native tide
#

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

native tide
#

for some reason my image doesn't show up when i launch my website to the heroku server

abstract geyser
#

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 ?

native tide
#

flask

abstract geyser
#

Ohhh.

#

I use Heroku as well, and whitenoise is the default package for static files. How does Heroku accommodate Flask application static files ?

native tide
#

does someone know how to keep two div on the same line

restive kindle
#

display: inline-block; vertical-align: top; OR display: flex;

dry pawn
heady echo
#

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.

dry pawn
#

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

heady echo
#

Yeah I wish I was able too but its for a client with an existing server ๐Ÿ˜ฆ

dry pawn
#

Ah, then it's not an option. I can't help you then ๐Ÿ˜”

heady echo
#

Thanks tho I wish I could help with yours but its honestly something I would like to know lol

toxic marten
#

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

native tide
#

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

pseudo halo
#

g u n i c o r n

rigid laurel
#

Goon icorn

bleak bobcat
#

Weird, I say u w s g i

gilded monolith
#

Guhnicorne

native tide
#

I also learned that wsgi is "whiskey" today

gilded monolith
#

i pronounce each letter of SQL when people call it "sequel" around me

#

i never know what to say

rigid laurel
#

It was originally called "structured English query language" so sequel made more sense

native tide
#

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

rigid laurel
#

Sequel is a good name though

native tide
#

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.

native tide
#

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

gilded monolith
#

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?

vagrant adder
#

^^

native tide
#

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.

tired root
#

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 ๐Ÿ˜„

native tide
#

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

tired root
#

If it does not cause any issues,then do what feels right for you

native tide
#

yeah both are the same thing. It just depends on which file you'd rather have the info on.

pliant falcon
#

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

bleak bobcat
#

Out of the box without any optimization/cache setup etc... Flask would probably be the fastest

stark yarrow
#

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

vagrant adder
#

Flask is the fastest out of those you pointed out just because it doesn't have almost no overhead @pliant falcon

tired root
#

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

pliant falcon
#

Thanks for the answers, actually if I create an contact form in flask is it means the website isnโ€™t static?

tired root
#

No, because there is dynamic code on the webserver. Static means there are only html files

vagrant adder
#

Yes

tired root
#

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

#

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

pliant falcon
#

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

tired root
#

You can use python to generate the html

#

Jekyll takes markdown and turns it into blog posts

pliant falcon
#

ahh

tired root
pliant falcon
#

cool

tired root
#

For example do you know github pages?

#

That uses jekyll

#

I've built that on my own on my RasPi

pliant falcon
#

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

tired root
#

which one?

pliant falcon
#

both

tired root
#

That is the power of pure html. NO delay for script execution

pliant falcon
#

so this Lektor and Jekyll are a differents ways to build websites with python?

tired root
#

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

pliant falcon
#

I actually really good with HTML and bootstrap.. the only thing I need is to build an contact form

tired root
#

do it in php

#

shouldn't be more than 10-20 lines

pliant falcon
#

and it's just for using cheaper servers? or it's diff in performance aswell?

tired root
#

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

pliant falcon
#

what is this?

tired root
#

Apache instructions for caching

pliant falcon
#

wow you giving me gold info that I didn't know

#

in wordpres for every thing I installed a plugin XD

tired root
#

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

pliant falcon
#

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

tired root
#

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

pliant falcon
#

bootstrap makes it easy for me to handke responsivity and designing beuatiful ui

tired root
#

That is your choice

#

I am just giving options

pliant falcon
#

thanks man

tired root
#

no problemo

west arrow
#

@tired root what do you mean by CPU cycles?

jagged lark
#

It is an instruction executed by the CPU

#

To simplify things, they just charge based on CPU usage

toxic marten
#

Which is the default margin for dl dt dd element in bootstrap?

rustic pebble
#

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

rustic pebble
#

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!

toxic marten
#

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๐Ÿ˜ฆ

rustic pebble
#

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

rigid laurel
#

just talk directly to their api

#

its all rest right?

rustic pebble
#

I will copy paste and adjust

#

@toxic marten I am not sure what can cause that

#

I know bootstrap but onlyto help myself :/

toxic marten
#

@rustic pebble im pre-intermediate. im mastering it

rustic pebble
#

Are you good on backend tho?

toxic marten
#

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

rustic pebble
#

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

toxic marten
rustic pebble
#

The problem is that is not using the paypal sdk

toxic marten
#

Ah. i really have no idea

rustic pebble
#

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

dry pawn
#

@rustic pebble you can use a context processor if you need a variable on every single page

rustic pebble
#

@dry pawn Thanks I will use that.

native tide
#

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?

dry pawn
#

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.

rustic pebble
#

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

native tide
#

Ok great

rustic pebble
#

๐Ÿ†

valid cypress
#

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.

bleak bobcat
#

I'm not sure I understand what you want/need, can you elaborate ?

jagged lark
#

@valid cypress you can set the default kward of your key

#

It act as a fallback if no value is provided for that key

bleak bobcat
#

But he's asking for rows, not columns/attributes, that's why I'm wondering what he really wants

jagged lark
#

I mean, a row is technically a model key

valid cypress
#

But this have 800+ entries

jagged lark
#

You have 800 entries in your model?

rustic pebble
#

Wow

#

Thats a lit

#

Lot*

valid cypress
#

PokeAPI have 800+ entries, that I want to my db

rustic pebble
#

800 entries as in 800 cols!

#

?*

jagged lark
#

Wait, you want to copy the entire PokรฉAPI db to your own database?

rustic pebble
#

I am sure you can do what you want witj an api

valid cypress
#

One endpoint

jagged lark
#

So you want to copy their database?

valid cypress
#

Basically, but in different format

jagged lark
#

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

valid cypress
#

I'm making Pokemon bot with Django admin panel. I want get things to DB only in first setup/start.

jagged lark
#

I mean, you are really going to spam the API with 800 requests at startup?

#

It seems kind of unreasonable

valid cypress
#

Only first startup

jagged lark
#

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

bleak bobcat
#

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

wild thunder
#

hey guys

#

i need to modify it

rustic pebble
#

@valid cypress why arent u just making on user command requests

valid cypress
#

Due then I'll have to do 5 request per command use.

rustic pebble
#

Can you give an example

#

Of a 5 user request

valid cypress
#

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

rustic pebble
#

Hmm

#

If you fetch one pokemon do you also get the attributes you sent?

jagged lark
#

You should do 5 requests per user request and use caching

#

Or it would takes way too much time to sync

rustic pebble
#

I would make a lazy db

#

Easiest and best

#

You only get what you need and it gets added to sql as well

native tide
#

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?

vagrant adder
#

filter

bleak bobcat
#

It's a filter

#

Some are built-in, some come from libraries (like crispy), and you can also create your own

rustic pebble
#

Is there anyway I can add a seperation line between Full Name - Email and Username - Password

#

Sorry for overlapping ur request @native tide

native tide
#

Its ok.

#

I'll have to look into how to make filters.

toxic marten
#

@rustic pebble do you mean an <hr>?

winter wren
#

@rustic pebble You mean a line break?

rustic pebble
#

I mean a horizontal line

#

that works as a seperator

#

yea an hr

#

I forgot about that

#

omg

toxic marten
#

Ok. Do you forgot about hr tag?