Skip to content
Snippets Groups Projects
Commit 13ee841a authored by Yifan Su's avatar Yifan Su
Browse files

Update 20 files

- /instance/database.db
- /website/auth.py
- /website/models.py
- /website/views.py
- /website/__init__.py
- /website/static/bird.png
- /website/static/index.html
- /website/static/img.jpg
- /website/static/style.css
- /website/templates/base.html
- /website/templates/home.html
- /website/templates/login.html
- /website/templates/profile.html
- /website/templates/sign_up.html
- /website/__pycache__/auth.cpython-39.pyc
- /website/__pycache__/models.cpython-39.pyc
- /website/__pycache__/views.cpython-39.pyc
- /website/__pycache__/__init__.cpython-39.pyc
- /README.md
- /main.py
parent c1185549
No related branches found
No related tags found
No related merge requests found
Showing
with 808 additions and 93 deletions
# c23025281_cmt120_cw2
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://git.cardiff.ac.uk/c23025281/c23025281_cmt120_cw2.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://git.cardiff.ac.uk/c23025281/c23025281_cmt120_cw2/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
flask
Flask-SQLAlchemy
flask-login
## Copyright and license
Code and documentation copyright 2011-2019 the [Bootstrap Authors](https://github.com/twbs/bootstrap/graphs/contributors) and [Twitter,
Inc.](https://twitter.com) Code released under the [MIT License](https://github.com/twbs/bootstrap/blob/master/LICENSE). Docs released
under [Creative Commons](https://creativecommons.org/licenses/by/3.0/).
The MIT License (MIT)
Copyright (c) 2011-2018 Twitter, Inc.
Copyright (c) 2011-2018 The Bootstrap Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------
MIT License
Copyright (c) 2021 Floating UI contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------
The MIT License (MIT)
Copyright (c) 2014 Call-Em-All
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------
Copyright OpenJS Foundation and other contributors, https://openjsf.org/
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
File added
from website import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import path
from flask_login import LoginManager
db = SQLAlchemy()
DB_NAME = "database.db"
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = '123456'
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
db.init_app(app)
from .views import views
from .auth import auth
app.register_blueprint(views, url_prefix='/')
app.register_blueprint(auth, url_prefix='/')
from .models import User, Post,Comment,Like
with app.app_context():
db.create_all()
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.init_app(app)
@login_manager.user_loader
def load_user(id):
return User.query.get(int(id))
return app
def create_database(app):
if not path.exists('website/' + DB_NAME):
db.create_all(app=app)
print('Created Database!')
File added
File added
File added
File added
from flask import Blueprint, render_template, request, flash, redirect, url_for
from .models import User
from werkzeug.security import generate_password_hash, check_password_hash
from . import db ##means from __init__.py import db
from flask_login import login_user, login_required, logout_user, current_user
auth = Blueprint('auth', __name__)
@auth.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
user = User.query.filter_by(username=username).first()
if user:
if check_password_hash(user.password, password):
flash('Logged in successfully!', category='success')
login_user(user, remember=True)
return redirect(url_for('views.home'))
else:
flash('Incorrect password, try again.', category='error')
else:
flash('Email does not exist.', category='error')
return render_template("login.html", user=current_user)
@auth.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('auth.login'))
@auth.route('/sign-up', methods=['GET', 'POST'])
def sign_up():
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
user = User.query.filter_by(username=username).first()
if user:
flash('Username already exists.', category='error')
else:
new_user = User(username=username, password=generate_password_hash(
password, method='pbkdf2:sha256'))
db.session.add(new_user)
db.session.commit()
login_user(new_user, remember=True)
flash('Account created!', category='success')
return redirect(url_for('views.home'))
return render_template("sign_up.html", user=current_user)
from . import db
from flask_login import UserMixin
from sqlalchemy.sql import func
from datetime import datetime
class Post(db.Model):
post_id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(200), nullable=False)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('user.user_id'))
comments = db.relationship('Comment', backref='post', lazy=True)
likes = db.relationship('Like', backref='post', lazy=True)
class User(db.Model, UserMixin):
user_id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(200), nullable=False)
password = db.Column(db.String(200), nullable=False)
posts = db.relationship('Post', backref='user', lazy=True)
comments = db.relationship('Comment', backref='user', lazy=True)
likes = db.relationship('Like', backref='user', lazy=True)
def get_id(self):
return str(self.user_id)
class Comment(db.Model):
comment_id = db.Column(db.Integer, primary_key=True)
comment_content = db.Column(db.String(200), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.user_id'))
post_id = db.Column(db.Integer, db.ForeignKey('post.post_id'))
class Like(db.Model):
like_id = db.Column(db.Integer, primary_key=True)
post_id = db.Column(db.Integer, db.ForeignKey('post.post_id'))
user_id = db.Column(db.Integer, db.ForeignKey('user.user_id'))
website/static/bird.png

55.7 KiB

website/static/img.jpg

885 KiB

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="bird.png">
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp"
>
<link rel="stylesheet" href="style.css">
<title>Resume</title>
</head>
<body>
<div class="container">
<div class="persSide">
<div class="profile">
<img src="img.jpg">
<h2>YIFAN SU<br><span>C23025281</span></h2>
</div>
<div class="info">
<h3 class="title">Profile</h3>
<ul>
<li>
<span class="material-icons">email</span>
<a href=mailto:suy32@cardiff.ac.uk><span class="text">SuY32@cardiff.ac.uk</span></a>
</li>
<li>
<span class="material-icons">home</span>
<span class="text">COMSC</span>
</li>
</ul>
</div>
</div>
<div class="rightSide">
<div class="about">
<h2 class="title2">Self-introduction</h2>
<p>I am a graduate student in MSc Computing with research interests in the field of artificial intelligence. I have an academic background in robotics and computing. I have a working knowledge of programming languages like Python and MATLAB. I maintain a positive attitude, willing to accept various challenges, eager to explore the unknown. My ambition is to contribute to academia and society.</p>
</div>
<div class="about skills">
<h2 class="title2">Skill</h2>
<div class="box">
<h4>HTML</h4>
<div class="percent">
<div style="width:80%"></div>
</div>
</div>
<div class="box">
<h4>JavaScript</h4>
<div class="percent">
<div style="width:70%"></div>
</div>
</div>
<div class="box">
<h4>Python</h4>
<div class="percent">
<div style="width:70%"></div>
</div>
</div>
<div class="box">
<h4>C/C++</h4>
<div class="percent">
<div style="width:50%"></div>
</div>
</div>
<div class="box">
<h4>MATLAB</h4>
<div class="percent">
<div style="width:60%"></div>
</div>
</div>
</div>
<div class="about">
<h2 class="title2">Work Product</h2>
<div class="box">
<div class="text">
<h4>CMT119 Assignment: static Web pages</h4>
<p></p>
<a href=https://project.cs.cf.ac.uk/SuY32/CMT119_Assessment/Guide.html>https://project.cs.cf.ac.uk/SuY32/CMT119_Assessment/Guide.html</a>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
\ No newline at end of file
* {
margin: 0;
padding:0;
box-sizing: border-box;
}
body {
background-color: rgb(226 140 244 / 27%);
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.container {
position: relative;
width:100%;
max-width: 1200px;
max-height: 1000px;
background-color: #fff;
margin: 50px;
display: grid;
grid-template-columns: 300px auto;
}
.container .persSide {
position: relative;
background-color: rgb(184 138 239);
padding:50px;
}
.profile {
position:relative;
display:flex;
flex-direction: column;
align-items: center;
padding-bottom: 10px;
border-bottom: 1px solid rgb(255 255 255);
}
.profile img{
width:150px;
height:150px;
border-radius: 50%;
}
.profile h2 {
color: #ffffff;
font-size: 20px;
margin-top: 20px;
text-align: center;
font-weight: 550;
line-height: 30px;
}
.profile h2 span {
font-size: 0.7em;
font-weight: 400;
}
.info {
padding-top: 30px;
}
.info .title {
color:#fff;
margin-bottom: 20px;
}
.info ul li {
position: relative;
list-style: none;
margin: 10px 0;
color:#fff;
}
.info ul li a {
cursor: pointer;
color:#fff;
}
.material-icons {
width: 30px;
font-size: 18px;
color: white;
}
.container .rightSide {
position: relative;
background-color: white;
padding:50px;
}
.about {
margin-bottom: 70px;
}
.title2 {
color:rgb(162 101 234 / 76%);
margin-bottom: 10px;
}
.about .box {
display: flex;
margin: 20px 0;
min-width: 150px;
}
.skills .box {
position:relative;
width: 100%;
display: grid;
grid-template-columns: 100px 1fr;
justify-content: center;
align-items: center;
}
.skills .box .percent {
position: relative;
width: 100%;
height: 10px;
background-color: rgb(233, 186, 243);
}
.skills .box .percent div {
position: absolute;
height: 100%;
background-color: rgb(162 101 234 / 76%);
}
@media (max-width:900px) {
.container {
margin: 10px;
grid-template-columns: repeat(1,1fr);
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
crossorigin="anonymous"
/>
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
crossorigin="anonymous"
/>
<title>{% block title %}Home{% endblock %}</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<button
class="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#navbar"
>
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbar">
<div class="navbar-nav">
{% if user.is_authenticated %}
<a class="nav-item nav-link" id="home" href="/">Home</a>
<a class="nav-item nav-link" id="profile" href="../static/index.html" target="_blank">Portfolio</a>
<a class="nav-item nav-link" id="profile" href="/profile">Profile</a>
<a class="nav-item nav-link" id="logout" href="/logout">Logout</a>
{% else %}
<a class="nav-item nav-link" id="profile" href="../static/index.html" target="_blank">Portfolio</a>
<a class="nav-item nav-link" id="login" href="/login">Login</a>
<a class="nav-item nav-link" id="signUp" href="/sign-up">Sign Up</a>
{% endif %}
</div>
</div>
</nav>
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %} {% for category, message in messages %} {% if category == 'error' %}
<div class="alert alert-danger alter-dismissable fade show" role="alert">
{{ message }}
<button type="button" class="close" data-dismiss="alert">
<span aria-hidden="true">&times;</span>
</button>
</div>
{% else %}
<div class="alert alert-success alter-dismissable fade show" role="alert">
{{ message }}
<button type="button" class="close" data-dismiss="alert">
<span aria-hidden="true">&times;</span>
</button>
</div>
{% endif %} {% endfor %} {% endif %} {% endwith %}
<div class="container">{% block content %} {% endblock %}</div>
<script
src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous"
></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"
></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"
></script>
</body>
</html>
{% extends "base.html" %} {% block title %}Home{% endblock %}
{% block content%}
<h1 align="center">Posts</h1>
<ul class="list-group list-group-flush" id="posts">
{% for post in posts %}
<li class="list-group-item">
Posted by {{post_user_mapping[post.post_id].username}} at {{post.date_created}}:<br>
{{ post.content }}
<div align="right">
<form method="POST" action="{{ url_for('views.like_post', post_id=post.post_id) }}">
<button type="submit" class="btn btn-primary">{{ post.likes|length }} Like(s)</button>
</form>
</div>
<button type="button" class="btn btn-primary" data-toggle="collapse" data-target="#comments{{ post.post_id }}">
Show Comments({{post.comments|length}})
</button>
<div id="comments{{ post.post_id }}" class="collapse">
<!-- Display existing comments -->
{% for comment in post.comments %}
<p>{{ post_user_mapping[comment.user_id].username }}: {{ comment.comment_content }}</p>
{% endfor %}
<form method="POST" action="{{ url_for('views.add_comment', post_id=post.post_id) }}">
<textarea name="comment" id="comment" class="form-control"></textarea>
<br />
<div align="center">
<button type="submit" class="btn btn-primary">Add a Comment</button>
</div>
</form>
</li>
{% endfor %}
</ul>
<form method="POST" onsubmit="return refreshPage();">
<textarea name="post" id="post" class="form-control"></textarea>
<br />
<div align="center">
<button type="submit" class="btn btn-primary">Publish a Post</button>
</div>
</form>
{% endblock %}
{% extends "base.html" %} {% block title %}Login{% endblock %}
{% block content%}
<form method="POST">
<h3 align="center">Login</h3>
<div class="form-group">
<label for="username">Username</label>
<input
type="username"
class="form-control"
id="username"
name="username"
placeholder="Enter username"
/>
</div>
<div class="form-group">
<label for="password">Password</label>
<input
type="password"
class="form-control"
id="password"
name="password"
placeholder="Enter password"
/>
</div>
<br />
<button type="submit" class="btn btn-primary">Login</button>
</form>
{% endblock %}
{% extends 'base.html' %} {% block title %}Profile{% endblock %}
{% block content %}
<h3 align="center">Welcome {{user.username}}, you can view and edit your posts here</h3>
<ul class="list-group list-group-flush" id="user_posts">
{% for post in user_posts %}
<li class="list-group-item">
You posted at {{post.date_created}}:
{{ post.content }}
<div align="right">
<form method="POST" action="{{ url_for('views.like_post', post_id=post.post_id) }}">
<button type="submit" class="btn btn-primary">{{ post.likes|length }} Like(s)</button>
</form>
<form method="POST" action="{{ url_for('views.delete_post', post_id=post.post_id) }}">
<button type="submit" class="btn btn-primary">Delete</button>
</form>
</div>
<button type="button" class="btn btn-primary" data-toggle="collapse" data-target="#comments{{ post.post_id }}">
Show Comments({{post.comments|length}})
</button>
<div id="comments{{ post.post_id }}" class="collapse">
<!-- Display existing comments -->
{% for comment in post.comments %}
<p>{{ comment.comment_content }} - {{ post_user_mapping[comment.user_id].username }}</p>
{% endfor %}
<form method="POST" action="{{ url_for('views.add_comment', post_id=post.post_id) }}">
<textarea name="comment" id="comment" class="form-control"></textarea>
<br />
<div align="center">
<button type="submit" class="btn btn-primary">Add a Comment</button>
</div>
</form>
</li>
{% endfor %}
</ul>
{% endblock %}
{% extends "base.html" %} {% block title %}Sign Up{% endblock %}
{% block content %}
<form method="POST">
<h3 align="center">Sign Up</h3>
<div class="form-group">
<label for="username">Username</label>
<input
type="username"
class="form-control"
id="username"
name="username"
placeholder="Enter username"
/>
</div>
<div class="form-group">
<label for="password1">Password</label>
<input
type="password"
class="form-control"
id="password"
name="password"
placeholder="Enter password"
/>
</div>
<br />
<button type="submit" class="btn btn-primary">Submit</button>
</form>
{% endblock %}
from flask import Blueprint, render_template, request, flash, jsonify,redirect,url_for
from flask_login import login_required, current_user
from .models import Post,Like,Comment,User
from . import db
import json
views = Blueprint('views', __name__)
@views.route('/', methods=['GET', 'POST'])
@login_required
def home():
allPosts = Post.query.all()
post_user_mapping = {}
for post in allPosts:
user = User.query.filter_by(user_id=post.user_id).first()
post_user_mapping[post.post_id] = user
if request.method == 'POST':
post = request.form.get('post')#Gets the note from the HTML
if len(post) < 1:
flash('Post is too short!', category='error')
else:
new_note = Post(content = post, user_id=current_user.user_id) #providing the schema for the note
db.session.add(new_note) #adding the note to the database
db.session.commit()
flash('Post published!', category='success')
return redirect(request.referrer or url_for('views.home'))
return render_template("home.html", user = current_user, posts = allPosts, post_user_mapping =post_user_mapping)
@views.route('/add_comment/<int:post_id>', methods=['POST'])
@login_required
def add_comment(post_id):
post = Post.query.get(post_id)
if post:
comment_content = request.form.get('comment')
if comment_content and len(comment_content) >= 1:
new_comment = Comment(comment_content=comment_content, user_id=current_user.user_id, post_id=post_id)
db.session.add(new_comment)
db.session.commit()
return redirect(request.referrer or url_for('views.home'))
@views.route('/like/<int:post_id>', methods=['POST'])
@login_required
def like_post(post_id):
post = Post.query.get(post_id)
if post:
existing_like = Like.query.filter_by(user_id=current_user.user_id, post_id=post_id).first()
if existing_like:
# User already liked the post, unlike it
db.session.delete(existing_like)
flash('Post unliked!', category='success')
else:
# User hasn't liked the post, like it
new_like = Like(user_id=current_user.user_id, post_id=post_id)
db.session.add(new_like)
flash('Post liked!', category='success')
db.session.commit()
return redirect(request.referrer or url_for('views.home'))
@views.route('/delete/<int:post_id>', methods=['POST'])
@login_required
def delete_post(post_id):
existing_post = Post.query.filter_by(post_id = post_id).first()
db.session.delete(existing_post)
db.session.commit()
flash('Post deleted!', category='success')
return redirect(url_for('views.profile'))
@views.route('/profile', methods=['GET', 'POST'])
@login_required
def profile():
user_posts = Post.query.filter_by(user=current_user).all()
user_comments = Comment.query.filter_by(user=current_user).all()
post_user_mapping = {}
for post in user_posts:
user = User.query.filter_by(user_id=post.user_id).first()
post_user_mapping[post.post_id] = user
return render_template("profile.html", user=current_user, user_posts=user_posts, user_comments=user_comments,post_user_mapping=post_user_mapping)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment