Posts not showing up on home page in Flask

<strong>The Goal</strong>

The Goal

I'm creating a Flask website to serve as the UI for a custom bioinformatics pipeline. The way I'm trying to design it is such that the user fills in the pipeline parameters (e.g. Project Name, Data Type, Number of Samples, etc.) in a multi-page form (kind of like the checkout process in online ordering) and then I would like these parameters to be saved to the user's account page as separate "posts".

The Issue

I've been following a Flask Tutorial online (https://www.youtube.com/watch?v=QnDWIZuWYW0&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH&index=2) about how to save the "posts" (pipeline parameters) to the user's dashboard by supplying fake or sample "posts" to the dashboard's html template, but nothing shows up at all. What am I doing wrong?

The Source Code

routes.py:

posts = [
            {
                'username': 'claudiadast',
                'date_posted': 'September 22, 2018',
                'stack_name': 'wgs-test-stack',
                'start_point': 'fastq',
                'input_uri': 's3://pipeline-validation/smallfq/',
                'build': 'GRCh38',
                'ome': 'wgs',
                'project_id': 'summerwater598'
            },
            {
                'username': 'claudiadast',
                'date_posted': 'September 10, 2018',
                'stack_name': 'clinical-exome',
                'start_point': 'fastq',
                'input_uri': 's3://pipeline-validation/Clinex/',
                'build': 'GRCh38',
                'ome': 'wes',
                'project_id': 'summerwater598'
            }
        ]

@app.route('/')
@app.route('/home')
def home():
return render_template('home.html', posts=posts)

home.html:

{% extends "layout.html" %}
{% block content %}
{% for post in posts %}
<h1>{{ post.stack_name }}</h1>
<p>{{ post.username }} on {{ post.date_posted }}</p>
<p>Pipeline Parameters:</p>
<p>{{ post.stack_name }}</p>
<p>{{ post.start_point }}</p>
<p>{{ post.input_uri }}</p>
<p>{{ post.build }}</p>
<p>{{ post.ome }}</p>
<p>{{ post.project_id }}</p>
{% endfor %}
{% endblock content %}

layout.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Psychcore Pipeline</title>
<link rel="stylesheet" href="static/site.css"
</head>
<body>
{% include 'includes/_navbar.html' %}
<div class="container">
{% block body %}{% endblock %}
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ category }}">
{{ message }}
</div>
{% endfor %}
{% endif %}
{% endwith %}
</div>

    &lt;script src='https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js'&gt;&lt;/script&gt;
&lt;/body&gt;

</html>


How to Sending form data to a template on flask

I'm trying to create a login page and have managed to get each separate page working but when you click "Login" it should take you to a profile page and when you click "Register" it should take you back to login. This does not happen and instead comes up with the 'can't reach this page'. How can I use flask to send the data from the template and render a new page?

I'm trying to create a login page and have managed to get each separate page working but when you click "Login" it should take you to a profile page and when you click "Register" it should take you back to login. This does not happen and instead comes up with the 'can't reach this page'. How can I use flask to send the data from the template and render a new page?

Python:

from flask import Flask, request, render_template
import sqlite3
from flask import g

app = Flask(name)

DATABASE = './users.db'

def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
return db

@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()

def query_db(query, args=(), one=False): #connects html with
cur = get_db().execute(query, args)
rv = cur.fetchall()
cur.close()
return (rv[0] if rv else None) if one else rv

def valid_login(username, password):
user = query_db('select * from User where username = ? and password = ?', [username, password], one=True)
if user is None:
return False
else:
return True

def log_the_user_in(username):
return render_template('profile.html', username=username)

def register_user(name, email, username, password):
query_db('INSERT INTO users (username, password, email, name) VALUES' '(%s, %s, %s, %s)',
(username, password, email, name))

@app.route("/")
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
if valid_login(request.form['username'], request.form['password']):
return log_the_user_in(request.form['username'])
else:
error = 'Invalid username/password'

return render_template('login.html', error=error)

@app.route('/register', methods=['POST', 'GET'])
def register():
if request.method == 'POST':
register_user(request.form['name'], request.form['email'], request.form['username'], request.forn['password'])
return render_template('login.html', error=None)

return render_template('Register.html', error=None)

if name == "main":
app.run()

Html:

<html>

&lt;head&gt;

    &lt;link rel="stylesheet" href="../static/form-style.css"&gt;



    &lt;script&gt;

    function validateForm() {

    var x = document.forms["login-form"]["username"].value;

    if (x==null || x=="") {

        alert("Name must be filled out");

        return false;

    }

    var y = document.forms["login-form"]["password"].value;

    if (y==null || y=="") {

        alert("Password name must be filled out");

        return false;

    }

    }



    &lt;/script&gt;



&lt;/head&gt;

&lt;body&gt;

    &lt;div&gt;

            &lt;form name="login-form"  action="/login" onsubmit="return validateForm()" target="_self" method="POST"  &gt;

                &lt;h2&gt;Login:&lt;/h2&gt;


                &lt;input type ="text" name ="username" placeholder="Username"&gt;&lt;br&gt;

                &lt;input type="password" name="password" placeholder="Password"&gt;&lt;br&gt;

                &lt;input type="submit" value="Submit"&gt;&lt;br&gt;

            &lt;/form&gt;

    &lt;/div&gt;

&lt;/body&gt;

</html>

 Does anyone have a clue about how to edit? Thanks in advance.

Issue making an AJAX call to flask render_template

Suppose that I have two radio buttons (labeled 1 and 2) and some text at the bottom of the page. By default the value is&nbsp;-1&nbsp;for the text and no check boxes are selected. If I click one of the radio buttons I want to change the value of the text to be either 1 or 2 depending on the radio input that was selected. To do so I have based the code on the&nbsp;<a href="https://stackoverflow.com/a/24891804/667648" target="_blank">AJAX call described here</a>. Here is the code:

Suppose that I have two radio buttons (labeled 1 and 2) and some text at the bottom of the page. By default the value is -1 for the text and no check boxes are selected. If I click one of the radio buttons I want to change the value of the text to be either 1 or 2 depending on the radio input that was selected. To do so I have based the code on the AJAX call described here. Here is the code:

hello.py

from flask import (
    Flask, render_template, request
)

app = Flask(name)

@app.route('/', methods=('GET', 'POST'))
def hello():
level = -1
print(request.method)
if request.method == 'POST':
level = int(request.form.get('level', False))
return render_template('test.html', value=level)

templates/test.html

<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<body>
<form>
<input name="level" type="radio" id="1">1</input>
<input name="level" type="radio" id="2">2</input>
</form>
{{ value }}
</body>
<script>
$(function() {
$('input[type=radio]').change(function() {
console.log( $( this ).attr("id"));
$.ajax({
type: "POST",
data: { level: $( this ).attr("id") },
success: function(response) {
console.log("HERE");
document.write(response);
},
});
});
});
</script>
</html>

When I call flask run, selecting either radio button will change the value to either 1 or 2 but I cannot select either radio button a second time. The page will hang on the second selection, and I am not sure what is going on.

Note: Although this may seem like overkill, I have a more complex form submission in the larger project I am working on, this is simply a MVCE.

Render HTML with Vanilla JavaScript and lit-html

Render HTML with Vanilla JavaScript and lit-html

Sometimes you need to render HTML elements on a web page. And like Goldilocks' search for "just right", you have to try a few techniques before you find the right one. Using a framework may be too hard. Using pure HTML and the DOM API may be too soft. What you need is something in the middle that is just right. Is lit-html "just right"? Let's find out.

Sometimes you need to render HTML elements on a web page. And like Goldilocks' search for "just right", you have to try a few techniques before you find the right one. Using a framework may be too hard. Using pure HTML and the DOM API may be too soft. What you need is something in the middle that is just right. Is lit-html "just right"? Let's find out.

First, I'll show how this all works. Then at the end of this article, I'll explain everything you need to get started with lit-html to try this for yourself.

When you're done, you can push your HTML app with lit-html to the cloud to see it in all of its glory! I included a link to a free Azure trial, so you can try it yourself.

Resources:

The Sample App

Here is the app I'll demonstrate in this article. It fetches a list of heroes and renders them when you click the button. It also renders a progress indicator while it is fetching.

What's the Value of lit-html

When you focus on rendering content, and nothing else, lit-html is a good fit. It works closely with the DOM to render content, and refresh it in an optimal manner. The docs can provide you with more details, but the basic code for lit-html looks like this.

// Credit: As seen in official docs https://lit-html.polymer-project.org/guide/getting-started

// Import lit-html
import { html, render } from 'lit-html';

// Define a template
const myTemplate = name =>
  html`
    <p>Hello ${name}</p>
  `;

// Render the template to the document
render(myTemplate('World'), document.body);

You import lit-html, define a template, then render it to the DOM. That's it!

Rendering HTML

A progress bar is fairly basic. There is some HTML, and we show it when needed and hide it when it is not required. While we could use a template, or innerHTML, or the DOM API for this, let's see what this would look like with lit-html.

First, we get a reference to the element in the DOM where the progress bar will appear.

Then we define the template. This code looks and feels like JSX (or TSX). The advantage here is that you can write the HTML. You wrap the HTML in a template string (notice the back-tick character is used and not a single quote). Template strings allow you to span lines and insert variables where needed (we'll see this soon). The magic that makes this work is the html tag that precedes the template string. The html tag is what tells lit-html that you are about to define a template.

Next, we compile the template and pass those results to lit-html's render function, which places the results in the DOM. Finally, we hide or show the progress bar as needed.

function showProgress(show = true) {
  const container = document.getElementById('progress-placeholder');

  const template: () => TemplateResult = () => html`
    <progress class="progress is-medium is-info" max="100"></progress>
  `;
  const result = template();
  render(result, container);

  container.style.display = show ? 'block' : 'none';
}

Now you can run this showProgress function any time you want to show the progress bar.

Note that when a template is re-rendered, the only part that is updated is the data that changed. If no data changed, nothing is updated.

Rendering HTML with Dynamic Values

The progress bar does not change each time it is rendered. You will have situations where you want your HTML to change. For example, you may have a message area on your web app that shows a styled message box with a title and a message. The title and message will change every time you show the message area. Now you have dynamic values.

The HTML is defined with a template string, so it is trivial to add a variable into it. Notice the code below adds a title and text into the template, using the ${data.title} and ${data.text} syntax, respectively.

Then the template is compiled and rendered were needed.

When this template is re-rendered, the only part that is updated is the data that changed. In this case, that's the title and text.

function showMessage(text: string, title = 'Info') {
  const template: (data: any) => TemplateResult = (data: Message) => html`
    <div id="message-box" class="message is-info">
      <h3 class="message-header">${data.title}</h3>
      <p class="message-body">${data.text}</p>
    </div>
  `;

  const el = document.getElementById('message-placeholder');
  const result = template({ title, text });
  render(result, el);

  el.style.visibility = !!text ? 'visible' : 'hidden';
}

Rendering a List

Things get a little more real when we render a list. Let's think about that for a moment. A list requires that we have a plan if there is data and a backup plan if there is no data. A list requires that we render the same thing for each row, and we don't know how many rows we have. A list requires that we pass different values for each row, too. Then we have to take the rows and wrap them in a container such as a <ul> or a <table>.

So there is a little more logic here, regardless of whether we use lit-html or any other technique. Let's explore how the replaceHeroList function renders the rows using lit-html.

function replaceHeroList(heroes?: Hero[]) {
 const heroPlaceholder = document.querySelector('.hero-list');

 // Define the template
 let template: () => TemplateResult;

 if (heroes && heroes.length) {
   // Create the template for every hero row
   template = createList();
 } else {
   // Create the template with a simple "not found" message
   template = () =>
     html`
       <p>heroes not found</p>
     `;
 }

 // Compile the template
 const result = template();

 // Render the template
 render(result, heroPlaceholder);

Notice that when there are heroes, we call the createList function. This function begins by creating an array of TemplateResult. So for every hero in the heroes array, we define a template that represents the <li> containing the HTML that displays that respective hero.

Then we create another template that contains the <ul> and embeds the array of hero templates. It's pretty cool that we can embed templates like this! Finally, we return it all and let the logic compile the templates and render them.

function createList() {
  // Create an array of the templates for each hero
  const templates: TemplateResult[] = heroes.map(hero => {
    return html`
      <li>
        <div class="card">
          <div class="card-content">
            <div class="content">
              <div class="name">${hero.name}</div>
              <div class="description">${hero.description}</div>
            </div>
          </div>
        </div>
      </li>
    `;
  });

  // Create a template that includes the hero templates
  const ulTemplate: () => TemplateResult = () =>
    html`
      <ul>
        ${templates}
      </ul>
    `;
  return ulTemplate;
}

Summary

When you want to render HTML, lit-html is a fast and light-weight option. Is it better than using templates and the DOM API? You'll have to decide what is best for you. But the real story here is that you have another great option to consider when determining the right tool for your job.

Prologue

You can also get editor help with your lit-html templates. Notice the image below shows the syntax highlighting for the HTML template!

Setup

You can install the lit-html package with npm.

npm install lit-html

Alternately you can load it directly from the unpkg.com CDN

import { html, render } from 'https://unpkg.com/lit-html?module';

You have a choice here. npm is my preference, but feel 100% free to use the CDN if that suits you.

TypeScript and lit-html

You only need to include the library for lit-html and you're done. But I like to use TypeScript, and I absolutely recommend enabling your tooling to work great with typeScript and lit-html.

Let me be very clear here - you do not need TypeScript. I choose to use it because it helps identify mistakes while I write code. If you don't want TypeScript, you can opt to use plain JavaScript.

Here are the steps to make TypeScript and lit-html light up together:

  1. Install TypeScript support for lit-html
  2. Configure your tsconfig.json file
  3. Install the VS Code extension for lit-html

Run this command to install the plugin and typescript, as development dependencies to your project.

npm install --save-dev typescript-lit-html-plugin typescript

Edit your tsconfig.json by adding the following to your compilerOptions section.

"compilerOptions": {
  "plugins": [
    {
      "name": "typescript-lit-html-plugin"
    }
  ]
}

Finally, install the VS Code extension for lit-html.

Now you get syntax highlighting for all of your lit-html templates!