Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
Design pattern for server-side (Flask) rendered variabled in javascript module files

I run a Flask web app where I have a domain model (this example Thing) which properties (e.g. rating) could be updated via a HTTP PATCH request. In my development setup I hard coded the API URL where the request must be made to, but this becomes an open source self hosted app so the URL must be generated & set by Flask.

<script type="module">
import {Thing} from './things.js';

// This string must be available inside the Thing class
// The {{ }} syntax with url_for is Flask/Jinja template style (server side)
const API_URL = '{{ url_for('thing_update', id='{0}' }}';

let stars = document.querySelectorAll('.rating .star')
stars.addEventListener('click', function(el){
  // To create an object with object properties, like its id
  let thing = new Thing({{ thing.id }});
  thing.rating = el.getAttribute('value');
})
</script>

My module looks like:

class Entity {
    _API_URL = '';

    async update (data) {
        let response = await fetch(this._API_URL, {
            method: 'PATCH',
            headers: {'Content-Type': 'application/json;charset=utf-8'},
            body: JSON.stringify(data)
        })

        if (!response.ok) {
            throw new Error(`Server response ${response.status}: `)
        } else if (response.status == 204) {
            console.debug('Response success, no content')
            return true
        } else {
            let json = await response.json()
            console.debug('Response success, body content: ', json)
            return json
        }
    }
}

class Thing extends Entity {
    _id = null;
    _rating = null;

    constructor(id) {
        super()

        this._id = id
        // How to get the proper API URL here???
        this._API_URL = super._API_URL.format(id)
    }

    set rating(value) {
        this._rating = value
        this.update()
    }

    async update() {
        console.debug('Update rating to ' + this._rating)
        super.update({rating: this._rating})
    }
}

export {Thing}

I have experience in server side coding (php/python etc) and it just feels "wrong" to set the API URL via the constructor or setter method on the object instance. This should be something as constant on the class level.

However, because I use Flask and don't use javascript for a SPA or something, I struggle how to get this "right". Is there any best practice for this case?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda