How to setup a web server on Mac

Homebrew 

Before the installation, we have to install homebrew first. Click here to see official guide.

Requirements

  • An Intel CPU 
  • OS X 10.11 or higher 
  • Command Line Tools (CLT) for Xcode: xcode-select --install, developer.apple.com/downloads or Xcode
  • A Bourne-compatible shell for installation (e.g. bash or zsh)

$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Flask

1. Install Python/Python3

$ brew install python
Checking Python version
$ python --version
$ python3 --version

2. Install Virtaulenv 

Why use virtualenv? 
Virtualenv is a virtual Python environment isolated from other Python development, incapable of interfering with or being affected by other Python programs on the same machine. Having different version of libraries for different projects Solves the elevated privillege issue as virtualenv allows you to install with user permission
$ sudo pip install virtualenv
$ virtualenv --version

3. Creating Virtual environment

$ virtualenv targetDirectory
$ cd targetDirectory

4. Activate the Virtualenv environment

$ source bin/activate

5. Install Flask

$ pip install Flask
$ pip install humanize

6. Hello, Flask Create a new file called app.py.

from flask import Flask
  
app = Flask(__name__)
  
@app.route('/')
def index():
    return 'Hello, Flask!'
  
if __name__ == '__main__':
    app.run(debug=True)
Open Open the web browser with http://localhost:5000.

Option: install file server. 

In the directory of flask:
$ git clone https://github.com/Wildog/flask-file-server
$ cd flask-file-server

Create a public folder which will put files for public.

$ mkdir public
Edit file_server.py and change the root path at line 13: from
root = os.path.expanduser('~')
to public folder
root = os.path.expanduser('~/targetDirectory/public')
Then save the changes, and enter public folder.
Now we can put files in the public folder and check out in the browser with http://localhost:8000.

Option2: Flask-cors 

Since you've activated Virtualenv environment, you can simply issue the following command to install additional packages.
$ pip install flask-cors
Import the package in python code.
from flask_cors import CORS

Node.js 

Alternative way to setup web server is using Node.js and http-server module.
$ brew install nodejs
$ mkdir targetDirectory
$ cd targetDirectory
$ npm install http-server -g
$ mkdir public
$ http-server ./public
Usage: http-server [path] [options] [path]
defaults to ./public if the folder exists, and ./ otherwise. Now you can visit http://localhost:8080 to view your server

References: 


Share:

0 意見:

張貼留言