about 2 years ago

Julien Phalip gave a great talk at DjangoCon 2015, he introduced three ways to hydrate (i.e. load initial data into React component on first page load) React app with data, I am going to quote him directly from the slides and add my own comments.

  1. Conventional Method: Client fetches data via Ajax after initial page load.

    Load the data via ajax after initial page load.

  2. Less conventional method: Server serializes data as global Javascript variable in the inital HTML payload (see Instagram).

    Let the server load the data first, then put it into a global Javascript variable which is embed inside the returned HTML page.

    In the linked Github project (which is a Django project), the server fetches from the database to get all of the data. Then, it converts the data from Python object to json format and embed the data in the returned HTML page.

  3. Server side rendering: Let the server render the output HTML with data and send it to the client.

    This one is a little bit involved. Django would pass the data from DB along with the React component to python-react for rendering.

    python-react is a piece of code that runs on a simple Node HTTP server and what it does is receiving the react component along with data via a POST request and returns the rendered HTML back. (The pyton-react server runs on the same server as your Django project.)

So which method to use then?

We can use the number of round trips and the rendering speed as metrics for the judgement.

Method 1

Round trips: The inital page request is one round trip, and the following ajax request is another one. So two round trips.

Rendering time: Server rendering is usually faster then client rendering, but if the amount of data gets rendered is not a lot then this time can be considered negligible. In this case, the rednering happens on the client side. Let's assume the amount of data need to be rendered is small and doesn't impact the user experience, then it is negligible.

Method 2

Round trips: Only one round trip

Rendering time: Negligible as aforementioned.

Method 3

Round trips: Only one round trip

Rendering time: If it is negligible on the client side then it is probably negligible on the server side.

It seems that Method 2 & 3 are equally fast. The differences between them are:

  • Method 2 renders on the client side and Method 3 renders on the server side.
  • Method 3 requires extra setup during development and deployment. Also, the more moving pieces there are, the more likely it breaks and takes longer to debug.

Conclusion

Without hard data to prove, here is just my speculation: Use Method 2 most of the time and only Method 3 if you think rendering on the client side is going to be slow and impact the user experience.

 
about 2 years ago

A lot of react projects hosted on github use ES6/7 syntax. I had a lot of headaches when reading them since I am not familiar with the new syntax. I decided to learn it by converting a simple react project written in ES5 to ES6. I documented the transitions I made while conveting it to ES6/7.

Importing React

ES5

var React = require('react');
var ReactPropTypes = React.PropTypes;

ES6

import React, {Component, PropTypes} from 'react';

To understand why there is no '{}' around React, let's take a look at react's source code:

var React = {
  ...
  Component: ReactComponent,   // both Component and PropTypes are like 'plain exports' in ES6

  PropTypes: ReactPropTypes,
  ...
}

module.exports = React;  /* this line is like the default export in ES6 */

In ES6, when importing a default export, there is no need to wrap it around {}, everything else has to be inside {}

Creating React Component and Exporting it

ES5

var Header = React.createClass({
    render: function() {
        return (
            <header>
                <h1>This is the header section</h1>
            </header>
        );
    }
});

module.exports = Header;

ES6

export default class Header extends Component {
    render() {
        return (
            <header>
                <h1>This is the header section</h1>
            </header>
        );
    }
}

You can use 'export default' if you don't care how the Header component will be named when it is imported, or use 'export' instead if you want to enforce its name.

PropTypes

ES5

var React = require('react');
var ReactPropTypes = React.PropTypes;

var Header = React.createClass({
    propTypes: {
      title: ReactPropTypes.string.isRequired
    }
});

ES6

import React, {Component, PropTypes} from 'react';

export default class Header extends Component {
    render() {
        return (
            <header>
                <h1>This is the header section</h1>
            </header>
        );
    }
}

//Note that the propTypes has to be defined outside of the class definition

Header.propTypes = {
    title: PropTypes.string.isRequired
}

The ES6 syntax looks weird because the propTypes section is outside of the class definition. This is due to the fact that only methods can be defined inside a class in ES6. If you want to define properties, they have to be outside of the class.

To avoid this issue, I prefer to use ES7 Property Initialiazers:

ES7

import React, {Component, PropTypes} from 'react';

export default class Header extends Component {

    // brings the propTypes inside the class definition

    // Note that propTypes belongs to the class, and thus it is static

    // non-static properties (instance properties) is shown in the next section

    static propTypes = {
        title: PropTypes.string.isRequired
    }

    render() {
        return (
            <header>
                <h1>This is the header section</h1>
            </header>
        );
    }
}

getInitialState

ES5

var Header = React.createClass({
    getInitialState: function() {
        return {
            title: this.props.title
        };
    },
});

ES6

export default class Header extends Component {
    constructor(props) {    /* Note props is passed into the constructor in order to be used */
        super(props);
        this.state = {
            title: props.title
        };
    }
}

To furthur simplify this code using ES7's property initializer:

ES7

export default class Header extends Component {
    // instance property

    state = {
        title: this.props.title
    };
    
    // followed by constructor...

}

Invoking Methods

Let's borrow an example from the offical react tutorial:

ES5

var Header = React.createClass({
    handleClick: function(event) {
        this.setState({liked: !this.state.liked});  // Note here that **this** is automatically bind to the componenet itself

    }
});

However in ES6, the React team decided to not automatically bind this to the component. So to rewrite the code above in ES6, we need to bind the handleClick function to the component inside the constructor:

ES6

export default class Header extends Component {
    constructor() { 
        super();
        this.handleClick = this.handleClick.bind(this);
    }
    
    handleClick(event) {
        this.setState({liked: !this.state.liked});  
    }
}

The React blog also suggested to use ES7 property initializers to make it even simpler:

ES7

export default class Header extends Component {
    handleClick = (event) => {
        this.setState({liked: !this.state.liked});  
    }
}

This code needs some explanation. The handleClick = ... part is ES7 property initializer stuff. The (event) => {} is ES6 fat arrow function which preserves this context when it is called.

There are quite a few ways to accomplish this using es6/7 but this is the simpliest way recommended by the React team.

Conclusion

These are the conversions needed to convert your code from ES5 to ES6/7. The new syntax reduces the amount of code and makes it look better IMO. It is definitely a good time to start learning the new syntax and using it in React.

 
about 2 years ago

UPDATE: A video tutorial of this post has been created by webucator. They also offer a set of Python online training classes.

Thanks to this SO post, here are the ways to shallow and deep copy lists in Python:

Shallow Copy (from fastest to slowest)

new_list = old_list[:]
new_list = [] 
new_list.extend(old_list)
new_list = list(old_list)
import copy

new_list = copy.copy(old_list)
new_list = [i for i in old_list]
new_list = []

for i in old_list:
    new_list.append(i)

Deepcopy (the slowest)

import copy

new_list = copy.deepcopy(old_list)
 
about 2 years ago

A few weeks ago, I wrote a blog on how to setup ST3 for React dev. Since then, I learned more about react development, I started to use eslint. Jslint is great but it does not support JSX. We need a linter that can be integrated with ST3 and show live linting result while coding. This is where eslint comes in.

Install eslint

You can install it either globally or locally. I installed it globally:

npm install -g eslint eslint-plugin-react

The only hiccup to start using eslint is its stunning numbers of configurable options available. I have included a .eslintrc file to get your started(Just copy and paste this code your your .eslintrc file). The majority of this file is based on this example and this project. I added/modified the following:

  • Enable JSX linting via eslint-plugin-react
  • Enable ES6 syntax
  • Enable ES6 module import and export
  • Use single quote instead of double quote around strings (you can always change this by replacing "quotes": [1, "single"] with "quotes": [1, "double"]. Just search for the quotes keyword.

A note about eslint's syntax, eslint use 0, 1 and 2 to represent:

  • 0 - disable the rule
  • 1 - display warning when a rule is violated
  • 2 - display error when a rule is violated

You can always look up a eslint setting here.

Enable eslint in Sublime Text 3 (ST3)

  1. Make sure SublimeLinter3 is installed first.
  2. Install SublimeLinter-eslint
  3. Make sure you have a .eslintrc file in your current project's root folder. Open up the project folder in sublime and wait for a few seconds for eslinter to kick in.

[Optional] Disable jshint in ST3

If you also have sublime-jshint installed, you want to disable it otherwise both jshint and eslint will lint your project. To do this, inside ST3, save your project by (Project -> Save project as ...). This will create a .sublime-project file, inside this file, put the following config inside:

{

    "SublimeLinter":{
        "linters":{
            "eslint":{
                "excludes":[
                    "dist/*",
                    "node_modules/*"
                ]
            },
            "jshint":{
                "@disable":true
            }
        }
    }
}

This config tells SublimeLinter to:

  1. disable jshint
  2. tell eslint to ignore your dist and node_modules folder

Note

Whenever you modify the .eslintrc file, it will NOT take effect unless your restart ST3. Also, when ST3 is opened, it will not respond to any user input for a few seconds because eslint is working in the background linting your files.

 
over 2 years ago

While setting the timezone for a Django server, I made a stupid mistake in the settings.py file:

TIME_ZONE = 'Asia/Shanghai'
USE_TZ = True

There is nothing wrong with the parameter names and syntax. After loading up the server, Django keeps using UTC time despite the fact that I have set TIME_ZONE = 'Asia/Shanghai'

The problem is caused by placing TIME_ZONE above USE_TZ. The order of these two lines matter here. The right way to do is:

USE_TZ = True
TIME_ZONE = 'Asia/Shanghai'
 
over 2 years ago

According to wikipedia, a closure is:

a technique for implementing lexically scoped name binding in languages with first-class functions.

I don't think this mouthful definition is comprehensible to anybody learning the language. So I decide to break it down and explain it in plain language.

Lexical Scope

Lexical scope = static scope, it refers to

determining a variable's scope based solely on its position within the textual corpus of code.

An example to illustrate this concept:

foo = 1; //a global variable that can be accessed from anywhere within the program


function log()
{
    var bar = 2; //a local variable can be only accessed by the function log itself

}

We can determine where foo and bar can be accessed within the program by looking at the code. Thus, the scopes of the variables are determined statically.

To contrast it with dynamic scope:

function log() {
    console.log(x); //resolve variable x at runtime (i.e. dynamically)
}

function print(){
    var x = getUserInput();
    log(); 
}

The value of x is not determined until runtime. Thus, console.log(x) has no idea what will be printed out. Also, x is neither a globally variable nor is defined within the log function. But log has access to it.

Note: this example above does not work in Javascript because JS does not support dynamic scoping.

So now we understand what the fancy term lexical scope means, let's take a look at the definition of first-class function

First-Class Function

A language supports:

  • passing functions as arguments to other functions
  • returning them as the values from other functions
  • assigning them to variables
  • storing them in data structures.

This one is easy to understand:

function isBigEnough(value) {
  return value >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); // the filter function expects a function being passed in as a parameter

I am not going to provide an example for each bullet point. But you get the idea. Passing, storing and returning functions are very common in Javascript.

Closure

According to this explanation,

Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure 'remembers' the environment in which it was created.

function outer(){
    var x = 5;  // the so called 'free' variable that can be accessed by inner()

    function inner(){
        console.log(x);
    }
    return inner;
}

var test = outer(); // outer() actually returns inner(), thus exposing inner() to the outside world

test(); // output 5

Highlights of this example:

  • inner() has access to variable x, which is defined outside of it
  • var test = outer() is equivalent of var test = inner() but test has no access to x
  • The value of x is stored in memory so that any subsequent call of test() will print 5

So to summarize what a closure is:

  • A function f that is nested within another function

- f accesses variables defined in the outer function

During the research of closure, another term comes up often:

Higher-order function

A function that does at least one of the following:

  • takes one or more functions as an input
  • outputs a function

So outer() is an example of a higher-order function because it outputs a function. The Mapfunction of a Javascript array is also a higher-order function because it takes a function as input.

 
over 2 years ago

I was given a task to randomly generate usernames and passwords for 80 users in Django. Here is how I did it:

Thanks to this excellent StackOverflow post, generating random characters become very easy:

import string
import random

def generate(size=5, numbers_only=False):
    base =  string.digits if numbers_only else string.ascii_lowercase + string.digits
    return ''.join(random.SystemRandom().choice(base) for _ in range(size))

I want to use lowercase characters for usernames and digits only for passwords. Thus, the optional parameter numbers_only is used to specific which format I want.

Then, open up the Django shell:

./manage.py shell

and Enter the following to the interactive shell to generate a user:

from django.contrib.auth.models import User
from note import utils

User.objects.create_user(utils.generate(), password=utils.generate(6, True))

I saved the generate() inside utils.py which is located inside a project named note. Modify from note import utils to suit your needs.

 
over 2 years ago

Use the --log-file=- option to send error messages to console:

gunicorn --log-file=-

After debugging is complete, remove this option and output the error message to a log file instead.

 
over 2 years ago

I have found a tool that allows you to write and test Javascript quickly in iPython Notebook. The tool is called IJavascript. The project page has a very detailed installation guide for differet OS.

To install it on Mac:

1) Install ijavascript itself via npm:

npm install -g ijavascript

2) Install the dependencies via pip:

sudo pip install --upgrade ipython jinja2 jsonschema pyzmq

3) to run:

ipython ijs

Here is a screenshot of it running:

 
over 2 years ago

The default npm list command not only list the packages installed locally but also the packages they depend on. To most users, showing packages dependency is not necessary, as most of the time, we only want to know what is installed. To fix this, the --depth=0 option can be used:

npm ls --depth=0

So we get the list on the left instead of on the right:

dir_name@1.0.0 /path/blah/blah                 dir_name@1.0.0 /path/blah/blah
|-- babel-core@5.8.3                           |-- babel-core@5.8.3
                                                   |- babel-plugin-constant-folding@1.0.1
                                                   |- babel-plugin-eval@1.0.1
                                                   ...

However, this is not enough. Because if you have installed a package either

You are likely to see these errors:

npm ERR! max depth reached: webpack@*, required by babel-loader@5.3.2   // this error is caused by installing webpack globally
npm ERR! extraneous: file-loader@0.8.4 /blah/file-loader   // this error is caused by using npm install instead of npm install --save

To ignore these errors, a solution provided by this blog works:

npm ls --depth=0 "$@" 2>/dev/null

To create a proper shorcut, open your .bash_profile (for Mac):

alias nl="npm ls --depth=0 "$@" 2>/dev/null"
alias nlg="npm ls -g --depth=0 "$@" 2>/dev/null"  #for listing global packages

Reload the .bash_profile file and that's it!

. .bash_profile