Latest Posts

Using React in a Flask Template

Nov 09,2017 at 11:23 am By Ben Hutton

You can use React from within the Flask templating engine. Since React isn't a framework (it is a library) you can integrate it in other Frameworks. Even those using other languages, like the Python framework Flask. The way it is done below it can be used in pretty much and other framework that has a web compatible view.

I was recently experimenting using React from within the Flask templating engine.  The code I was using was from this tutorial.  While I certainly like the idea of what this code does, it is it is not very useful as is since the array used for the search in hard coded.  

After playing around with it for a while and reading more than a couple of online discussions I worked out how to set the variable from within the template. This in effect will allow Flask to pass variables into the React scripts.

All you need to do to get the array declaration into Flask is move the declaration of countries variable from the Javascript file and move it into the Flask template. The function as per the tutorial looks like the following. The improved version is below this:

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find....... Read More
                        

Now to finish things off.  All that’s left is to setup the User Profile view and allow adding Comments.  Again starting off with tests.

The first article in this series can be found here.

Starting off with Comments

UserTest.php

public function testAddComment()
{
    $this->withoutMiddleware();
    $user = $this->authenticateUser();

    factory(Posts::class)->create(
        [
            'author_id' => 1,
            'id' => 1,
            'title' => 'test34534',
            'body' => '123',
            'slug' => 'test234234',
            'active' => True,
        ]);

    $comment = factory(Posts::class)->raw(
        [
            'body' => 'some text',
            'on_post' => 1
        ]);

    $response = $this->actingAs($user)->post('/comment/add', $comment);
    $response->assertStatus(302);
}

CommentController.php

<?php

namespace App\Http\Controllers;

use App\Posts;
use App\Comments;
use Redirect;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class CommentController extends Controller
{
    /**
     * Display create post form
     *
     * @param Request $request
     * @return $this|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function add(Request $request)
    {
        return....... Read More
                        

Now we extend the main functionality of the site that we started in the previous post.  We can create a user and a post, now we add the ability to List, Edit and Delete  posts.  We will be creating two list views.  One for the main page that lists the latest 5, the other being under the users profile listing all their posts.

<?php

namespace Tests\Unit;

use Tests\TestCase;
use App\User;
use App\Posts;
use Illuminate\Foundation\Testing\DatabaseMigrations;


class PostTestWithoutMiddleware extends TestCase
{
    use DatabaseMigrations;

    /**
     * Check user can login and see new-post form
     */
    public function testNewPostGet()
    {
        $user = $this->authenticateUser();

        $this->actingAs($user)
            ->withSession(['foo' => 'bar'])
            ->get('new-post')
            ->assertSuccessful();
    }

    /**
     * Check invalid login/nologin cannot open /new-post
     */
    public function testCreateNewPostInvalidUser()
    {
        $user = factory(User::class)->create();

        $this->actingAs($user)
            ->withSession(['users' => 'fred bloggs'])
            ->get('/new-post')
            ->assertStatus(302);
    }

    /**
     * Check valid user can open /new-post
     */
    public function testNewPostCreation()
    {
        $this->withoutMiddleware();....... Read More
                        

Now to get on to building functionality.  The first item on the list is to create a post.  For this to work we will need to be able to mock new users and the actual post data.  The first test we will write is to check that the site presents the form for creating a new post.

Note:  If this is the first article in the series please start at the beginning.

Tests for new post form

<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\User;
use App\Posts;
use Illuminate\Foundation\Testing\DatabaseMigrations;


class PostTestWithoutMiddleware extends TestCase
{
    use DatabaseMigrations;

    /**
     * Check user can login and see new-post form
     */
    public function testNewPostGet()
    {
        $user = $this->authenticateUser();

        $this->actingAs($user)
            ->withSession(['foo' => 'bar'])
            ->get('new-post')
            ->assertSuccessful();
    }

    /**
     * Check invalid login/nologin cannot open /new-post
     */
    public function testCreateNewPostInvalidUser()
    {
        $user = factory(User::class)->create();

        $this->actingAs($user)
            ->withSession(['users' => 'fred bloggs'])
            ->get('/new-post')
            ->assertStatus(302);
    }

    /**
     * Check valid user can open /new-post
     */
    public function tes....... Read More
                        

Next is to configure the tests.  This article assumes you have a working Laravel setup, if not please go to my previous article. As per TDD you write your tests first.  Laravel makes this really easy, once you know how.  All you have to do is run the following command to setup a test class.

# php artisan make:test RouteTest

This will create the file RouteTest.php under tests/Feature.  Within this you can create the routing and authentication tests as follows:

<?php

namespace Tests\Unit;

use Tests\TestCase;
use App\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class RouteTest extends TestCase
{
    use DatabaseMigrations;

    public function testRoot()
    {
        $this->assertTrue(true);
        $response = $this->get('/');
        $response->assertStatus(200);
        $response->assertSee('Laravel');
    }

    public function testHomeShowsLogin()
    {
        $this->assertTrue(true);
        $response = $this->get('/home');
        $response->assertStatus(302);
        $response->assertSee('/login');
    }

    public function testHomeLogsIn()
    {
        $password = '1qazwsx'; // Our password

        $user = factory(User::class)->create([
            'name' => 'fred',
            'email' => 'taylor@laravel.com',
            'password' => bcrypt($password) // Save t....... Read More
                        

Copyright © 2017 | Ben Hutton