HackMIT 2020 Beginner Workshop
go.hackmit.org/beginner-slides
A Few Important Announcements
Welcome to Beginner Workshop!
Let’s Get Started!
We recommend you:
If you fall behind:
Workshop 1: Setup + Basics
What is version control?
What is git?
What is GitHub?
Install git
Create a GitHub account
Key Concept: Snapshots
Key Concept: Commit
Key Concept: Repository
Key Concept: Branches
What does a branch look like?
Time
How do you branch from master?
Time
How do you branch from master?
Time
Key Concept: Merging
Time
How do you make a commit?
Adding a Commit
The Remote Repository
Workshop 1, Part 2: HTML/CSS
HackBook!
Features:
HTML / CSS
The HTML Tag
<div></div>
<div id=”this is unique” class=”not unique” blah=”random”></div>
<div id=”my-second-div” class=”not unique” blah=”random”></div>
<div blah=”random”></div>
Important Attributes:
Important Tags to Know
<p>A paragraph goes here</p>
<h1>Large header</h1>
<h2>Medium header</h2>
...
<h6>Smaller header</h3>
<a href=”link to smthn”></a>
<img src=”link to image”>
HTML Structure
Definition - <html> </html>
It also identifies the beginning and end of the HTML document.
Header - <head> </head>
The header contains information about the document that will not appear on the actual page, such as the title of the document
Body - <body> </body>
The body tags contain all the information and other visible content on the page.
<!doctype html>
<html>
<head>
Metadata goes here
</head>
<body>
page content goes here
</body>
</html>
Code: Creating our page structure
Let’s make it pretty … CSS!
Selectors, basic styles
CSS Selectors
Tag Selector
div { }
Class Selector
.class { }
Id selector
#id { }
Combining them:
.facts p { }
Common Properties/Values:
Selectors Example
img { }
.some-text { }
#title { }
#second-text { }
<body>
<div id="container">
<h1 id="title">Justin</h1>
<img src="some image link">
<p class="some-text"></p>
<p id="second-text" class="some-text"></p>
<p class="some-text"></p>
</div>
</body>
Code: Adding CSS
Lowkey still kinda ugly tho?
Extension: Using Frameworks
Bootstrap
Semantic UI
Example: Semantic UI
Add this inside <head></head> before main.css
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
Add this inside <body></body> after all your content
<script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script>
Code: Making it even prettier
Thanks for coming!
Attendance Link: https://play.hackmit.org/attendance?id=8160
Beginner Workshop Part 2: Flask + JS!
go.hackmit.org/beginner-slides
A Few Important Announcements
Code from Workshop 1
Has been pushed to the workshop1 branch on the beginner repo!
git pull
git add .
git commit -m “this is my commit message”
git checkout workshop1
Text Editors:
Sublime Text: https://www.sublimetext.com/
Visual Studio Code: https://code.visualstudio.com/
The Language of the Internet
Using Postman
GET requests:
POST requests:
What does the Backend Do?
Client ⇐⇒ Frontend, Server ⇐⇒ Backend
Directory Structure
__init__.py
import os
from flask import Flask, session, request
app = Flask(__name__)
#load main config
app.config.from_pyfile('../config.py')
import my_app.views
Hello World?
Flask Templates
Jinja Templating
Code: Rendering Templates
Adding endpoints
Testing with Postman
[GET] /change_name:
[POST] /post :
{
"title":"Post title"
"description": "Post description"
}
Exercise: Can you make a “change_fact” endpoint?
Javascript & jQuery
Intro to JavaScript (ft. jQuery)
Using Developer Tools in your browser
Console is a JavaScript shell
Basic language features:
More useful language features!
let fruits = ['Apple', 'Banana'];
console.log(fruits.length);
console.log(fruits[0]);
for (let i = 0; i < n; i++) {
// your code here
}
for (let x : fruits) {
}
Interacting with HTML
document.getElementById("post1") -> selects and returns the element whose ID is “post1”
document.getElementsByTagName("p") -> selects and returns all elements that are a <p> type in an array
document.getElementsByClassName("className") -> select by class name
Changing HTML through JavaScript
Use div ids where possible! Don’t do this :)
jQuery?
$(document).ready(function(){
// jQuery methods go here...
});
Clicking things in jQuery
<head>
<title>Hack Book</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
<link rel="stylesheet" href="../static/main.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="../static/script.js"></script>
</head>
Create a new file in static/ called ‘script.js’ with the following contents. Add the post-button ID to the post button.
$(document).ready(function(){
$("#post-button").click(function(){
console.log("clicked!");
});
});
Main use of jQuery: get/post requests
$(document).ready(function(){
$("#post-button").click(function(){
const url = "http://localhost:5000/post";
const postInfo = {
title: "New title",
description: "This is my new post description"
};
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(postInfo),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: function() {
console.log("request complete!");
}
});
});
});
Adding dynamic input
In your HTML:
<input type="text" id="title"><br>
<input type="text" id="description">
<div class="ui button" id="post-button">Post</div>
In script.js:
const title = $("#title").val();
const description = $("#description").val();
const postInfo = {
title: title,
description: description
};
Refresh to see your page update!
Break Time!
Beginner Workshop 3: Databases and APIs
go.hackmit.org/beginner-slides
Code from Workshop 2
Has been pushed to the workshop2 branch on the beginner repo!
git pull
git add .
git commit -m “this is my commit message”
git checkout workshop2
If you’re stuck, stay after the workshop for Office Hours!
Why use a database?
Relational Databases are made of tables of rows and columns
id | name | value |
0 | “Birthday” | “Aug 29” |
1 | “Favorite Color” | “blue” |
2 | “Favorite hackathon” | “hackMIT” |
Facts
schema: the structure of the database
id | name | value |
0 | “Birthday” | “Aug 29” |
1 | “Favorite Color” | “blue” |
2 | “Favorite hackathon” | “hackMIT” |
Facts
SQL
SQLite
Databases in Flask
Let’s add a database to our example app!
import os��base = os.path.abspath(os.path.dirname(__file__))�SQLALCHEMY_DATABASE_URI = "sqlite:///" + os.path.join(base, 'app.db')�SQLALCHEMY_TRACK_MODIFICATIONS = False |
./config.py
import os, config�from flask import Flask, session, request�from flask_sqlalchemy import SQLAlchemy���app = Flask(__name__)��app.config.from_pyfile('../config.py') �db = SQLAlchemy(app)��import my_app.views |
./my_app/__init__.py
How do we define the schema of our database?
id | name | value |
Facts
./my_app/models.py
from my_app import db��class Fact(db.Model):� id = db.Column(db.Integer, primary_key=True)� name = db.Column(db.String(100))� value = db.Column(db.String(100))� |
SQLAlchemy Query
./my_app/views.py
@app.route("/")�def index():� db_facts = Fact.query.all()� fact_dict = {fact.name: fact.value for fact in db_facts}� return render_template("index2.html", name=name, facts=fact_dict, posts=posts) |
./my_app/views.py
@app.route("/change_facts", methods=["POST"])�def change_facts():� if request.method == "POST":� change_facts = request.get_json()� for key, value in change_facts.items():� if Fact.query.filter(Fact.name == key).first() is None:� new_fact = Fact(name=key, value=value)� db.session.add(new_fact)� db.session.commit()� return redirect("/") |
Exercise: implementing Posts!
./my_app/models.py
class Post(db.Model):� id = db.Column(db.Integer, primary_key = True)� title = db.Column(db.String(100))� description = db.Column(db.String(300)) |
@app.route("/")�def index():� db_facts = Fact.query.all()� db_posts = Post.query.all()� fact_dict = {fact.name: fact.value for fact in db_facts}� post_list = [{'title': post.title, 'description': post.description} for post in db_posts]� return render_template("index2.html", name=name, facts=fact_dict, posts=post_list)���@app.route("/post", methods=["POST"])�def post():� if request.method == "POST":� post_info = request.get_json()� new_post = Post(title=post_info['title'], description=post_info['description'])� db.session.add(new_post)� db.session.commit()� return redirect("/") |
./my_app/views.py
Adding a simple API
What is an API?
Let’s add the Cat API to our app!
Add Javascript File
Add a button and div for the image
Get your API key
Create the getCat() function
Connect our function to our button