Compare commits

..

20 Commits
2023 ... main

Author SHA1 Message Date
Miguel Grinberg 3472187155
Chapter 23: Application Programming Interfaces (APIs) (v0.23) 2022-11-11 12:57:54 +00:00
Miguel Grinberg bb2273349f
Chapter 22: Background Jobs (v0.22) 2022-11-11 12:56:46 +00:00
Miguel Grinberg a25d6f2f19
Chapter 21: User Notifications (v0.21) 2022-11-11 12:56:42 +00:00
Miguel Grinberg 7f32336d21
Chapter 20: Some JavaScript Magic (v0.20) 2022-11-11 12:52:59 +00:00
Miguel Grinberg b577aa6b62
Chapter 19: Deployment on Docker Containers (v0.19) 2022-11-11 12:52:59 +00:00
Miguel Grinberg 5cfb75def5
Chapter 18: Deployment on Heroku (v0.18) 2022-11-11 12:52:59 +00:00
Miguel Grinberg 94b40cf4b7
Chapter 17: Deployment on Linux (v0.17) 2022-11-11 12:52:59 +00:00
Miguel Grinberg 868ad4b410
Chapter 16: Full-Text Search (v0.16) 2022-11-11 12:52:58 +00:00
Miguel Grinberg f4a401e320
Chapter 15: A Better Application Structure (v0.15) 2022-11-11 12:52:55 +00:00
Miguel Grinberg 7f7c8ef5d7
Chapter 14: Ajax (v0.14) 2022-11-11 12:51:46 +00:00
Miguel Grinberg 8a56c34ce2
Chapter 13: I18n and L10n (v0.13) 2022-11-11 12:51:46 +00:00
Miguel Grinberg a650e6f989
Chapter 12: Dates and Times (v0.12) 2022-11-11 12:51:46 +00:00
Miguel Grinberg 542fa42312
Chapter 11: Facelift (v0.11) 2022-11-11 12:51:46 +00:00
Miguel Grinberg 14f6f99ea9
Chapter 10: Email Support (v0.10) 2022-11-11 12:51:46 +00:00
Miguel Grinberg fdeb27d052
Chapter 9: Pagination (v0.9) 2022-11-11 12:51:39 +00:00
Miguel Grinberg d1363e0326
Chapter 8: Followers (v0.8) 2022-11-06 00:38:59 +00:00
Miguel Grinberg 8f43aadd41
Chapter 7: Error Handling (v0.7) 2021-07-10 16:42:12 +01:00
Miguel Grinberg f9ba2d28cf
Chapter 6: Profile Page and Avatars (v0.6) 2021-07-10 16:42:12 +01:00
Miguel Grinberg e7b1227a1c
Chapter 5: User Logins (v0.5) 2021-07-10 16:42:12 +01:00
Miguel Grinberg 68368ea5c5
Chapter 4: Database (v0.4) 2021-07-10 16:42:12 +01:00
40 changed files with 456 additions and 552 deletions

View File

@ -1,2 +1 @@
FLASK_APP=microblog.py
FLASK_DEBUG=1

View File

@ -1,8 +1,13 @@
FROM python:slim
RUN useradd microblog
WORKDIR /home/microblog
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
RUN pip install gunicorn pymysql cryptography
RUN python -m venv venv
RUN venv/bin/pip install -r requirements.txt
RUN venv/bin/pip install gunicorn pymysql cryptography
COPY app app
COPY migrations migrations
@ -10,7 +15,9 @@ COPY microblog.py config.py boot.sh ./
RUN chmod a+x boot.sh
ENV FLASK_APP microblog.py
RUN flask translate compile
RUN chown -R microblog:microblog ./
USER microblog
EXPOSE 5000
ENTRYPOINT ["./boot.sh"]

4
Vagrantfile vendored
View File

@ -1,6 +1,6 @@
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/jammy64"
config.vm.network "private_network", ip: "192.168.56.10"
config.vm.box = "ubuntu/focal64"
config.vm.network "private_network", ip: "192.168.33.10"
config.vm.provider "virtualbox" do |vb|
vb.memory = "2048"
end

View File

@ -6,6 +6,7 @@ from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_mail import Mail
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_babel import Babel, lazy_gettext as _l
from elasticsearch import Elasticsearch
@ -13,17 +14,13 @@ from redis import Redis
import rq
from config import Config
def get_locale():
return request.accept_languages.best_match(current_app.config['LANGUAGES'])
db = SQLAlchemy()
migrate = Migrate()
login = LoginManager()
login.login_view = 'auth.login'
login.login_message = _l('Please log in to access this page.')
mail = Mail()
bootstrap = Bootstrap()
moment = Moment()
babel = Babel()
@ -36,8 +33,9 @@ def create_app(config_class=Config):
migrate.init_app(app, db)
login.init_app(app)
mail.init_app(app)
bootstrap.init_app(app)
moment.init_app(app)
babel.init_app(app, locale_selector=get_locale)
babel.init_app(app)
app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) \
if app.config['ELASTICSEARCH_URL'] else None
app.redis = Redis.from_url(app.config['REDIS_URL'])
@ -52,9 +50,6 @@ def create_app(config_class=Config):
from app.main import bp as main_bp
app.register_blueprint(main_bp)
from app.cli import bp as cli_bp
app.register_blueprint(cli_bp)
from app.api import bp as api_bp
app.register_blueprint(api_bp, url_prefix='/api')
@ -96,4 +91,9 @@ def create_app(config_class=Config):
return app
@babel.localeselector
def get_locale():
return request.accept_languages.best_match(current_app.config['LANGUAGES'])
from app import models

View File

@ -1,11 +1,9 @@
import os
from flask import Blueprint
import click
bp = Blueprint('cli', __name__, cli_group=None)
@bp.cli.group()
def register(app):
@app.cli.group()
def translate():
"""Translation and localization commands."""
pass

View File

@ -13,7 +13,7 @@ class EditProfileForm(FlaskForm):
submit = SubmitField(_l('Submit'))
def __init__(self, original_username, *args, **kwargs):
super().__init__(*args, **kwargs)
super(EditProfileForm, self).__init__(*args, **kwargs)
self.original_username = original_username
def validate_username(self, username):

View File

@ -38,7 +38,7 @@ def index():
flash(_('Your post is now live!'))
return redirect(url_for('main.index'))
page = request.args.get('page', 1, type=int)
posts = current_user.following_posts().paginate(
posts = current_user.followed_posts().paginate(
page=page, per_page=current_app.config['POSTS_PER_PAGE'],
error_out=False)
next_url = url_for('main.index', page=posts.next_num) \
@ -151,10 +151,9 @@ def unfollow(username):
@bp.route('/translate', methods=['POST'])
@login_required
def translate_text():
data = request.get_json()
return {'text': translate(data['text'],
data['source_language'],
data['dest_language'])}
return jsonify({'text': translate(request.form['text'],
request.form['source_language'],
request.form['dest_language'])})
@bp.route('/search')

View File

@ -24,7 +24,7 @@ class SearchableMixin(object):
for i in range(len(ids)):
when.append((ids[i], i))
return cls.query.filter(cls.id.in_(ids)).order_by(
db.case(*when, value=cls.id)), total
db.case(when, value=cls.id)), total
@classmethod
def before_commit(cls, session):
@ -84,10 +84,8 @@ class PaginatedAPIMixin(object):
followers = db.Table(
'followers',
db.Column('follower_id', db.Integer, db.ForeignKey('user.id'),
primary_key=True),
db.Column('followed_id', db.Integer, db.ForeignKey('user.id'),
primary_key=True)
db.Column('follower_id', db.Integer, db.ForeignKey('user.id')),
db.Column('followed_id', db.Integer, db.ForeignKey('user.id'))
)
@ -96,32 +94,26 @@ class User(UserMixin, PaginatedAPIMixin, db.Model):
username = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
password_hash = db.Column(db.String(128))
posts = db.relationship('Post', back_populates='author', lazy='dynamic')
posts = db.relationship('Post', backref='author', lazy='dynamic')
about_me = db.Column(db.String(140))
last_seen = db.Column(db.DateTime, default=datetime.utcnow)
token = db.Column(db.String(32), index=True, unique=True)
token_expiration = db.Column(db.DateTime)
following = db.relationship(
followed = db.relationship(
'User', secondary=followers,
primaryjoin=(followers.c.follower_id == id),
secondaryjoin=(followers.c.followed_id == id),
lazy='dynamic', back_populates='followers')
followers = db.relationship(
'User', secondary=followers,
primaryjoin=(followers.c.followed_id == id),
secondaryjoin=(followers.c.follower_id == id),
lazy='dynamic', back_populates='following')
backref=db.backref('followers', lazy='dynamic'), lazy='dynamic')
messages_sent = db.relationship('Message',
foreign_keys='Message.sender_id',
lazy='dynamic', back_populates='author')
backref='author', lazy='dynamic')
messages_received = db.relationship('Message',
foreign_keys='Message.recipient_id',
lazy='dynamic',
back_populates='recipient')
backref='recipient', lazy='dynamic')
last_message_read_time = db.Column(db.DateTime)
notifications = db.relationship('Notification', lazy='dynamic',
back_populates='user')
tasks = db.relationship('Task', lazy='dynamic', back_populates='user')
notifications = db.relationship('Notification', backref='user',
lazy='dynamic')
tasks = db.relationship('Task', backref='user', lazy='dynamic')
def __repr__(self):
return '<User {}>'.format(self.username)
@ -134,25 +126,27 @@ class User(UserMixin, PaginatedAPIMixin, db.Model):
def avatar(self, size):
digest = md5(self.email.lower().encode('utf-8')).hexdigest()
return f'https://www.gravatar.com/avatar/{digest}?d=identicon&s={size}'
return 'https://www.gravatar.com/avatar/{}?d=identicon&s={}'.format(
digest, size)
def follow(self, user):
if not self.is_following(user):
self.following.append(user)
self.followed.append(user)
def unfollow(self, user):
if self.is_following(user):
self.following.remove(user)
self.followed.remove(user)
def is_following(self, user):
return user in self.following
return self.followed.filter(
followers.c.followed_id == user.id).count() > 0
def following_posts(self):
following = Post.query.join(
def followed_posts(self):
followed = Post.query.join(
followers, (followers.c.followed_id == Post.user_id)).filter(
followers.c.follower_id == self.id)
own = Post.query.filter_by(user_id=self.id)
return following.union(own).order_by(Post.timestamp.desc())
return followed.union(own).order_by(Post.timestamp.desc())
def get_reset_password_token(self, expires_in=600):
return jwt.encode(
@ -251,9 +245,8 @@ class Post(SearchableMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.String(140))
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), index=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
language = db.Column(db.String(5))
author = db.relationship('User', back_populates='posts')
def __repr__(self):
return '<Post {}>'.format(self.body)
@ -261,14 +254,10 @@ class Post(SearchableMixin, db.Model):
class Message(db.Model):
id = db.Column(db.Integer, primary_key=True)
sender_id = db.Column(db.Integer, db.ForeignKey('user.id'), index=True)
recipient_id = db.Column(db.Integer, db.ForeignKey('user.id'), index=True)
sender_id = db.Column(db.Integer, db.ForeignKey('user.id'))
recipient_id = db.Column(db.Integer, db.ForeignKey('user.id'))
body = db.Column(db.String(140))
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
author = db.relationship('User', foreign_keys='Message.sender_id',
back_populates='messages_sent')
recipient = db.relationship('User', foreign_keys='Message.recipient_id',
back_populates='messages_received')
def __repr__(self):
return '<Message {}>'.format(self.body)
@ -277,10 +266,9 @@ class Message(db.Model):
class Notification(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128), index=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), index=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
timestamp = db.Column(db.Float, index=True, default=time)
payload_json = db.Column(db.Text)
user = db.relationship('User', back_populates='notifications')
def get_data(self):
return json.loads(str(self.payload_json))
@ -292,7 +280,6 @@ class Task(db.Model):
description = db.Column(db.String(128))
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
complete = db.Column(db.Boolean, default=False)
user = db.relationship('User', back_populates='tasks')
def get_rq_job(self):
try:

View File

@ -7,7 +7,7 @@ def add_to_index(index, model):
payload = {}
for field in model.__searchable__:
payload[field] = getattr(model, field)
current_app.elasticsearch.index(index=index, id=model.id, document=payload)
current_app.elasticsearch.index(index=index, id=model.id, body=payload)
def remove_from_index(index, model):
@ -21,8 +21,7 @@ def query_index(index, query, page, per_page):
return [], 0
search = current_app.elasticsearch.search(
index=index,
query={'multi_match': {'query': query, 'fields': ['*']}},
from_=(page - 1) * per_page,
size=per_page)
body={'query': {'multi_match': {'query': query, 'fields': ['*']}},
'from': (page - 1) * per_page, 'size': per_page})
ids = [int(hit['_id']) for hit in search['hits']['hits']]
return ids, search['hits']['total']['value']

View File

@ -7,9 +7,11 @@
</td>
<td>
{% set user_link %}
<a class="user_popup" href="{{ url_for('main.user', username=post.author.username) }}">
<span class="user_popup">
<a href="{{ url_for('main.user', username=post.author.username) }}">
{{ post.author.username }}
</a>
</span>
{% endset %}
{{ _('%(username)s said %(when)s',
username=user_link, when=moment(post.timestamp).fromNow()) }}
@ -19,8 +21,8 @@
<br><br>
<span id="translation{{ post.id }}">
<a href="javascript:translate(
'post{{ post.id }}',
'translation{{ post.id }}',
'#post{{ post.id }}',
'#translation{{ post.id }}',
'{{ post.language }}',
'{{ g.locale }}');">{{ _('Translate') }}</a>
</span>

View File

@ -1,9 +1,14 @@
{% extends 'base.html' %}
{% import "bootstrap_wtf.html" as wtf %}
{% import 'bootstrap/wtf.html' as wtf %}
{% block content %}
{% block app_content %}
<h1>{{ _('Sign In') }}</h1>
<div class="row">
<div class="col-md-4">
{{ wtf.quick_form(form) }}
</div>
</div>
<br>
<p>{{ _('New User?') }} <a href="{{ url_for('auth.register') }}">{{ _('Click to Register!') }}</a></p>
<p>
{{ _('Forgot Your Password?') }}

View File

@ -1,7 +1,11 @@
{% extends "base.html" %}
{% import "bootstrap_wtf.html" as wtf %}
{% import 'bootstrap/wtf.html' as wtf %}
{% block content %}
{% block app_content %}
<h1>{{ _('Register') }}</h1>
<div class="row">
<div class="col-md-4">
{{ wtf.quick_form(form) }}
</div>
</div>
{% endblock %}

View File

@ -1,7 +1,11 @@
{% extends "base.html" %}
{% import "bootstrap_wtf.html" as wtf %}
{% import 'bootstrap/wtf.html' as wtf %}
{% block content %}
{% block app_content %}
<h1>{{ _('Reset Your Password') }}</h1>
<div class="row">
<div class="col-md-4">
{{ wtf.quick_form(form) }}
</div>
</div>
{% endblock %}

View File

@ -1,7 +1,11 @@
{% extends "base.html" %}
{% import "bootstrap_wtf.html" as wtf %}
{% import 'bootstrap/wtf.html' as wtf %}
{% block content %}
{% block app_content %}
<h1>{{ _('Reset Password') }}</h1>
<div class="row">
<div class="col-md-4">
{{ wtf.quick_form(form) }}
</div>
</div>
{% endblock %}

View File

@ -1,30 +1,26 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
{% if title %}
<title>{{ title }} - Microblog</title>
{% else %}
<title>{{ _('Welcome to Microblog') }}</title>
{% endif %}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg bg-body-tertiary">
{% extends 'bootstrap/base.html' %}
{% block title %}
{% if title %}{{ title }} - Microblog{% else %}{{ _('Welcome to Microblog') }}{% endif %}
{% endblock %}
{% block navbar %}
<nav class="navbar navbar-default">
<div class="container">
<a class="navbar-brand" href="{{ url_for('main.index') }}">Microblog</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link" aria-current="page" href="{{ url_for('main.index') }}">{{ _('Home') }}</a>
</li>
<li class="nav-item">
<a class="nav-link" aria-current="page" href="{{ url_for('main.explore') }}">{{ _('Explore') }}</a>
</li>
<a class="navbar-brand" href="{{ url_for('main.index') }}">Microblog</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li><a href="{{ url_for('main.index') }}">{{ _('Home') }}</a></li>
<li><a href="{{ url_for('main.explore') }}">{{ _('Explore') }}</a></li>
</ul>
{% if g.search_form %}
<form class="navbar-form navbar-left" method="get" action="{{ url_for('main.search') }}">
<div class="form-group">
@ -32,35 +28,31 @@
</div>
</form>
{% endif %}
</ul>
<ul class="navbar-nav mb-2 mb-lg-0">
<ul class="nav navbar-nav navbar-right">
{% if current_user.is_anonymous %}
<li class="nav-item">
<a class="nav-link" aria-current="page" href="{{ url_for('auth.login') }}">{{ _('Login') }}</a>
</li>
<li><a href="{{ url_for('auth.login') }}">{{ _('Login') }}</a></li>
{% else %}
<li class="nav-item">
<a class="nav-link" aria-current="page" href="{{ url_for('main.messages') }}">{{ _('Messages') }}
<li>
<a href="{{ url_for('main.messages') }}">{{ _('Messages') }}
{% set new_messages = current_user.new_messages() %}
<span id="message_count" class="badge text-bg-danger"
<span id="message_count" class="badge"
style="visibility: {% if new_messages %}visible
{% else %}hidden{% endif %};">
{{ new_messages }}
</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" aria-current="page" href="{{ url_for('main.user', username=current_user.username) }}">{{ _('Profile') }}</a>
</li>
<li class="nav-item">
<a class="nav-link" aria-current="page" href="{{ url_for('auth.logout') }}">{{ _('Logout') }}</a>
</li>
<li><a href="{{ url_for('main.user', username=current_user.username) }}">{{ _('Profile') }}</a></li>
<li><a href="{{ url_for('auth.logout') }}">{{ _('Logout') }}</a></li>
{% endif %}
</ul>
</div>
</div>
</nav>
<div class="container mt-3">
{% endblock %}
{% block content %}
<div class="container">
{% if current_user.is_authenticated %}
{% with tasks = current_user.get_tasks_in_progress() %}
{% if tasks %}
@ -73,7 +65,6 @@
{% endif %}
{% endwith %}
{% endif %}
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
@ -81,78 +72,85 @@
{% endfor %}
{% endif %}
{% endwith %}
{% block content %}{% endblock %}
{# application content needs to be provided in the app_content block #}
{% block app_content %}{% endblock %}
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe" crossorigin="anonymous"></script>
{% endblock %}
{% block scripts %}
{{ super() }}
{{ moment.include_moment() }}
{{ moment.lang(g.locale) }}
<script>
async function translate(sourceElem, destElem, sourceLang, destLang) {
document.getElementById(destElem).innerHTML =
'<img src="{{ url_for('static', filename='loading.gif') }}">';
const response = await fetch('/translate', {
method: 'POST',
headers: {'Content-Type': 'application/json; charset=utf-8'},
body: JSON.stringify({
text: document.getElementById(sourceElem).innerText,
function translate(sourceElem, destElem, sourceLang, destLang) {
$(destElem).html('<img src="{{ url_for('static', filename='loading.gif') }}">');
$.post('/translate', {
text: $(sourceElem).text(),
source_language: sourceLang,
dest_language: destLang
})
})
const data = await response.json();
document.getElementById(destElem).innerText = data.text;
}
function initialize_popovers() {
const popups = document.getElementsByClassName('user_popup');
for (let i = 0; i < popups.length; i++) {
const popover = new bootstrap.Popover(popups[i], {
content: 'Loading...',
trigger: 'hover focus',
placement: 'right',
html: true,
sanitize: false,
delay: {show: 500, hide: 0},
container: popups[i],
customClass: 'd-inline',
}).done(function(response) {
$(destElem).text(response['text'])
}).fail(function() {
$(destElem).text("{{ _('Error: Could not contact server.') }}");
});
popups[i].addEventListener('show.bs.popover', async (ev) => {
if (ev.target.popupLoaded) {
return;
}
const response = await fetch('/user/' + ev.target.innerText.trim() + '/popup');
const data = await response.text();
const popover = bootstrap.Popover.getInstance(ev.target);
if (popover && data) {
ev.target.popupLoaded = true;
popover.setContent({'.popover-body': data});
$(function () {
var timer = null;
var xhr = null;
$('.user_popup').hover(
function(event) {
// mouse in event handler
var elem = $(event.currentTarget);
timer = setTimeout(function() {
timer = null;
xhr = $.ajax(
'/user/' + elem.first().text().trim() + '/popup').done(
function(data) {
xhr = null;
elem.popover({
trigger: 'manual',
html: true,
animation: false,
container: elem,
content: data
}).popover('show');
flask_moment_render_all();
}
);
}, 1000);
},
function(event) {
// mouse out event handler
var elem = $(event.currentTarget);
if (timer) {
clearTimeout(timer);
timer = null;
}
else if (xhr) {
xhr.abort();
xhr = null;
}
else {
elem.popover('destroy');
}
}
);
});
}
}
document.addEventListener('DOMContentLoaded', initialize_popovers);
function set_message_count(n) {
const count = document.getElementById('message_count');
count.innerText = n;
count.style.visibility = n ? 'visible' : 'hidden';
$('#message_count').text(n);
$('#message_count').css('visibility', n ? 'visible' : 'hidden');
}
function set_task_progress(task_id, progress) {
const progressElement = document.getElementById(task_id + '-progress');
if (progressElement) {
progressElement.innerText = progress;
$('#' + task_id + '-progress').text(progress);
}
}
{% if current_user.is_authenticated %}
function initialize_notifications() {
let since = 0;
setInterval(async function() {
const response = await fetch('{{ url_for('main.notifications') }}?since=' + since);
const notifications = await response.json();
for (let i = 0; i < notifications.length; i++) {
$(function() {
var since = 0;
setInterval(function() {
$.ajax('{{ url_for('main.notifications') }}?since=' + since).done(
function(notifications) {
for (var i = 0; i < notifications.length; i++) {
switch (notifications[i].name) {
case 'unread_message_count':
set_message_count(notifications[i].data);
@ -164,10 +162,10 @@
}
since = notifications[i].timestamp;
}
}, 10000);
}
document.addEventListener('DOMContentLoaded', initialize_notifications);
);
}, 10000);
});
{% endif %}
</script>
</body>
</html>
{% endblock %}

View File

@ -1,70 +0,0 @@
{% macro form_field(field, autofocus) %}
{%- if field.type == 'BooleanField' %}
<div class="form-check mb-3">
{{ field(class='form-check-input') }}
{{ field.label(class='form-check-label') }}
</div>
{%- elif field.type == 'RadioField' %}
{{ field.label(class='form-label') }}
{%- for item in field %}
<div class="form-check{% if loop.last %} mb-3{% endif %}">
{{ item(class='form-check-input') }}
{{ item.label(class='form-check-label') }}
</div>
{%- endfor %}
{%- elif field.type == 'SelectField' %}
{{ field.label(class='form-label') }}
{{ field(class='form-select mb-3') }}
{%- elif field.type == 'TextAreaField' %}
<div class="mb-3">
{{ field.label(class='form-label') }}
{% if autofocus %}
{{ field(class='form-control' + (' is-invalid' if field.errors else ''), autofocus=True) }}
{% else %}
{{ field(class='form-control' + (' is-invalid' if field.errors else '')) }}
{% endif %}
{%- for error in field.errors %}
<div class="invalid-feedback">{{ error }}</div>
{%- endfor %}
</div>
{%- elif field.type == 'SubmitField' %}
{{ field(class='btn btn-primary mb-3') }}
{%- else %}
<div class="mb-3">
{{ field.label(class='form-label') }}
{% if autofocus %}
{{ field(class='form-control' + (' is-invalid' if field.errors else ''), autofocus=True) }}
{% else %}
{{ field(class='form-control' + (' is-invalid' if field.errors else '')) }}
{% endif %}
{%- for error in field.errors %}
<div class="invalid-feedback">{{ error }}</div>
{%- endfor %}
</div>
{%- endif %}
{% endmacro %}
{% macro quick_form(form, action="", method="post", id="", novalidate=False) %}
<form novalidate
{%- if action != None %} action="{{ action }}"{% endif -%}
{%- if method %} method="{{ method }}"{% endif %}
{%- if id %} id="{{ id }}"{% endif -%}
{%- if novalidate %} novalidate{% endif -%}>
{{ form.hidden_tag() }}
{%- for field, errors in form.errors.items() %}
{%- if form[field].widget.input_type == 'hidden' %}
{%- for error in errors %}
<div class="invalid-feedback">{{ error }}</div>
{%- endfor %}
{%- endif %}
{%- endfor %}
{% set ns = namespace(first_field=true) %}
{%- for field in form %}
{% if field.widget.input_type != 'hidden' -%}
{{ form_field(field, ns.first_field) }}
{% set ns.first_field = false %}
{%- endif %}
{%- endfor %}
</form>
{% endmacro %}

View File

@ -1,7 +1,11 @@
{% extends "base.html" %}
{% import "bootstrap_wtf.html" as wtf %}
{% import 'bootstrap/wtf.html' as wtf %}
{% block content %}
{% block app_content %}
<h1>{{ _('Edit Profile') }}</h1>
<div class="row">
<div class="col-md-4">
{{ wtf.quick_form(form) }}
</div>
</div>
{% endblock %}

View File

@ -1,6 +1,3 @@
<!doctype html>
<html>
<body>
<p>Dear {{ user.username }},</p>
<p>
To reset your password
@ -13,5 +10,3 @@
<p>If you have not requested a password reset simply ignore this message.</p>
<p>Sincerely,</p>
<p>The Microblog Team</p>
</body>
</html>

View File

@ -1,6 +1,6 @@
{% extends "base.html" %}
{% block content %}
{% block app_content %}
<h1>{{ _('Not Found') }}</h1>
<p><a href="{{ url_for('main.index') }}">{{ _('Back') }}</a></p>
{% endblock %}

View File

@ -1,6 +1,6 @@
{% extends "base.html" %}
{% block content %}
{% block app_content %}
<h1>{{ _('An unexpected error has occurred') }}</h1>
<p>{{ _('The administrator has been notified. Sorry for the inconvenience!') }}</p>
<p><a href="{{ url_for('main.index') }}">{{ _('Back') }}</a></p>

View File

@ -1,23 +1,24 @@
{% extends "base.html" %}
{% import "bootstrap_wtf.html" as wtf %}
{% import 'bootstrap/wtf.html' as wtf %}
{% block content %}
{% block app_content %}
<h1>{{ _('Hi, %(username)s!', username=current_user.username) }}</h1>
{% if form %}
{{ wtf.quick_form(form) }}
<br>
{% endif %}
{% for post in posts %}
{% include '_post.html' %}
{% endfor %}
<nav aria-label="Post navigation">
<ul class="pagination">
<li class="page-item{% if not prev_url %} disabled{% endif %}">
<a class="page-link" href="#">
<nav aria-label="...">
<ul class="pager">
<li class="previous{% if not prev_url %} disabled{% endif %}">
<a href="{{ prev_url or '#' }}">
<span aria-hidden="true">&larr;</span> {{ _('Newer posts') }}
</a>
</li>
<li class="page-item{% if not next_url %} disabled{% endif %}">
<a class="page-link" href="#">
<li class="next{% if not next_url %} disabled{% endif %}">
<a href="{{ next_url or '#' }}">
{{ _('Older posts') }} <span aria-hidden="true">&rarr;</span>
</a>
</li>

View File

@ -1,19 +1,19 @@
{% extends "base.html" %}
{% block content %}
{% block app_content %}
<h1>{{ _('Messages') }}</h1>
{% for post in messages %}
{% include '_post.html' %}
{% endfor %}
<nav aria-label="Post navigation">
<ul class="pagination">
<li class="page-item{% if not prev_url %} disabled{% endif %}">
<a class="page-link" href="#">
<nav aria-label="...">
<ul class="pager">
<li class="previous{% if not prev_url %} disabled{% endif %}">
<a href="{{ prev_url or '#' }}">
<span aria-hidden="true">&larr;</span> {{ _('Newer messages') }}
</a>
</li>
<li class="page-item{% if not next_url %} disabled{% endif %}">
<a class="page-link" href="#">
<li class="next{% if not next_url %} disabled{% endif %}">
<a href="{{ next_url or '#' }}">
{{ _('Older messages') }} <span aria-hidden="true">&rarr;</span>
</a>
</li>

View File

@ -1,20 +1,20 @@
{% extends "base.html" %}
{% block content %}
{% block app_content %}
<h1>{{ _('Search Results') }}</h1>
{% for post in posts %}
{% include '_post.html' %}
{% endfor %}
<nav aria-label="Post navigation">
<ul class="pagination">
<li class="page-item{% if not prev_url %} disabled{% endif %}">
<a class="page-link" href="#">
<span aria-hidden="true">&larr;</span> {{ _('Newer posts') }}
<nav aria-label="...">
<ul class="pager">
<li class="previous{% if not prev_url %} disabled{% endif %}">
<a href="{{ prev_url or '#' }}">
<span aria-hidden="true">&larr;</span> {{ _('Previous results') }}
</a>
</li>
<li class="page-item{% if not next_url %} disabled{% endif %}">
<a class="page-link" href="#">
{{ _('Older posts') }} <span aria-hidden="true">&rarr;</span>
<li class="next{% if not next_url %} disabled{% endif %}">
<a href="{{ next_url or '#' }}">
{{ _('Next results') }} <span aria-hidden="true">&rarr;</span>
</a>
</li>
</ul>

View File

@ -1,7 +1,11 @@
{% extends "base.html" %}
{% import "bootstrap_wtf.html" as wtf %}
{% import 'bootstrap/wtf.html' as wtf %}
{% block content %}
{% block app_content %}
<h1>{{ _('Send Message to %(recipient)s', recipient=recipient) }}</h1>
<div class="row">
<div class="col-md-4">
{{ wtf.quick_form(form) }}
</div>
</div>
{% endblock %}

View File

@ -1,6 +1,6 @@
{% extends "base.html" %}
{% block content %}
{% block app_content %}
<table class="table table-hover">
<tr>
<td width="256px"><img src="{{ user.avatar(256) }}"></td>
@ -10,7 +10,7 @@
{% if user.last_seen %}
<p>{{ _('Last seen on') }}: {{ moment(user.last_seen).format('LLL') }}</p>
{% endif %}
<p>{{ _('%(count)d followers', count=user.followers.count()) }}, {{ _('%(count)d following', count=user.following.count()) }}</p>
<p>{{ _('%(count)d followers', count=user.followers.count()) }}, {{ _('%(count)d following', count=user.followed.count()) }}</p>
{% if user == current_user %}
<p><a href="{{ url_for('main.edit_profile') }}">{{ _('Edit your profile') }}</a></p>
{% if not current_user.get_task_in_progress('export_posts') %}
@ -20,14 +20,14 @@
<p>
<form action="{{ url_for('main.follow', username=user.username) }}" method="post">
{{ form.hidden_tag() }}
{{ form.submit(value=_('Follow'), class_='btn btn-primary') }}
{{ form.submit(value=_('Follow'), class_='btn btn-default') }}
</form>
</p>
{% else %}
<p>
<form action="{{ url_for('main.unfollow', username=user.username) }}" method="post">
{{ form.hidden_tag() }}
{{ form.submit(value=_('Unfollow'), class_='btn btn-primary') }}
{{ form.submit(value=_('Unfollow'), class_='btn btn-default') }}
</form>
</p>
{% endif %}
@ -40,15 +40,15 @@
{% for post in posts %}
{% include '_post.html' %}
{% endfor %}
<nav aria-label="Post navigation">
<ul class="pagination">
<li class="page-item{% if not prev_url %} disabled{% endif %}">
<a class="page-link" href="#">
<nav aria-label="...">
<ul class="pager">
<li class="previous{% if not prev_url %} disabled{% endif %}">
<a href="{{ prev_url or '#' }}">
<span aria-hidden="true">&larr;</span> {{ _('Newer posts') }}
</a>
</li>
<li class="page-item{% if not next_url %} disabled{% endif %}">
<a class="page-link" href="#">
<li class="next{% if not next_url %} disabled{% endif %}">
<a href="{{ next_url or '#' }}">
{{ _('Older posts') }} <span aria-hidden="true">&rarr;</span>
</a>
</li>

View File

@ -1,27 +1,32 @@
<div>
<img src="{{ user.avatar(64) }}" style="margin: 5px; float: left">
<table class="table">
<tr>
<td width="64" style="border: 0px;"><img src="{{ user.avatar(64) }}"></td>
<td style="border: 0px;">
<p><a href="{{ url_for('main.user', username=user.username) }}">{{ user.username }}</a></p>
<small>
{% if user.about_me %}<p>{{ user.about_me }}</p>{% endif %}
<div class="clearfix"></div>
{% if user.last_seen %}
<p>{{ _('Last seen on') }}: {{ moment(user.last_seen).format('lll') }}</p>
{% endif %}
<p>{{ _('%(count)d followers', count=user.followers.count()) }}, {{ _('%(count)d following', count=user.following.count()) }}</p>
<p>{{ _('%(count)d followers', count=user.followers.count()) }}, {{ _('%(count)d following', count=user.followed.count()) }}</p>
{% if user != current_user %}
{% if not current_user.is_following(user) %}
<p>
<form action="{{ url_for('main.follow', username=user.username) }}" method="post">
{{ form.hidden_tag() }}
{{ form.submit(value=_('Follow'), class_='btn btn-outline-primary btn-sm') }}
{{ form.submit(value=_('Follow'), class_='btn btn-default btn-sm') }}
</form>
</p>
{% else %}
<p>
<form action="{{ url_for('main.unfollow', username=user.username) }}" method="post">
{{ form.hidden_tag() }}
{{ form.submit(value=_('Unfollow'), class_='btn btn-outline-primary btn-sm') }}
{{ form.submit(value=_('Unfollow'), class_='btn btn-default btm-sm') }}
</form>
</p>
{% endif %}
{% endif %}
</div>
</small>
</td>
</tr>
</table>

View File

@ -10,8 +10,7 @@ def translate(text, source_language, dest_language):
return _('Error: the translation service is not configured.')
auth = {
'Ocp-Apim-Subscription-Key': current_app.config['MS_TRANSLATOR_KEY'],
'Ocp-Apim-Subscription-Region': 'westus'
}
'Ocp-Apim-Subscription-Region': 'westus2'}
r = requests.post(
'https://api.cognitive.microsofttranslator.com'
'/translate?api-version=3.0&from={}&to={}'.format(

View File

@ -1,2 +1,3 @@
[python: app/**.py]
[jinja2: app/templates/**.html]
extensions=jinja2.ext.autoescape,jinja2.ext.with_

View File

@ -9,4 +9,5 @@ while true; do
echo Deploy command failed, retrying in 5 secs...
sleep 5
done
flask translate compile
exec gunicorn -b :5000 --access-logfile - --error-logfile - microblog:app

View File

@ -10,6 +10,7 @@ class Config(object):
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', '').replace(
'postgres://', 'postgresql://') or \
'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
LOG_TO_STDOUT = os.environ.get('LOG_TO_STDOUT')
MAIL_SERVER = os.environ.get('MAIL_SERVER')
MAIL_PORT = int(os.environ.get('MAIL_PORT') or 25)

View File

@ -1,7 +1,8 @@
from app import create_app, db
from app import create_app, db, cli
from app.models import User, Post, Message, Notification, Task
app = create_app()
cli.register(app)
@app.shell_context_processor

View File

@ -18,15 +18,11 @@ depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('post', schema=None) as batch_op:
batch_op.add_column(sa.Column('language', sa.String(length=5), nullable=True))
op.add_column('post', sa.Column('language', sa.String(length=5), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('post', schema=None) as batch_op:
batch_op.drop_column('language')
op.drop_column('post', 'language')
# ### end Alembic commands ###

View File

@ -18,17 +18,13 @@ depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('user', schema=None) as batch_op:
batch_op.add_column(sa.Column('about_me', sa.String(length=140), nullable=True))
batch_op.add_column(sa.Column('last_seen', sa.DateTime(), nullable=True))
op.add_column('user', sa.Column('about_me', sa.String(length=140), nullable=True))
op.add_column('user', sa.Column('last_seen', sa.DateTime(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('user', schema=None) as batch_op:
batch_op.drop_column('last_seen')
batch_op.drop_column('about_me')
op.drop_column('user', 'last_seen')
op.drop_column('user', 'about_me')
# ### end Alembic commands ###

View File

@ -26,18 +26,12 @@ def upgrade():
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
with op.batch_alter_table('post', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_post_timestamp'), ['timestamp'], unique=False)
batch_op.create_index(batch_op.f('ix_post_user_id'), ['user_id'], unique=False)
op.create_index(op.f('ix_post_timestamp'), 'post', ['timestamp'], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('post', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_post_user_id'))
batch_op.drop_index(batch_op.f('ix_post_timestamp'))
op.drop_index(op.f('ix_post_timestamp'), table_name='post')
op.drop_table('post')
# ### end Alembic commands ###

View File

@ -19,11 +19,10 @@ depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('followers',
sa.Column('follower_id', sa.Integer(), nullable=False),
sa.Column('followed_id', sa.Integer(), nullable=False),
sa.Column('follower_id', sa.Integer(), nullable=True),
sa.Column('followed_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['followed_id'], ['user.id'], ),
sa.ForeignKeyConstraint(['follower_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('follower_id', 'followed_id')
sa.ForeignKeyConstraint(['follower_id'], ['user.id'], )
)
# ### end Alembic commands ###

View File

@ -28,26 +28,14 @@ def upgrade():
sa.ForeignKeyConstraint(['sender_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
with op.batch_alter_table('message', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_message_recipient_id'), ['recipient_id'], unique=False)
batch_op.create_index(batch_op.f('ix_message_sender_id'), ['sender_id'], unique=False)
batch_op.create_index(batch_op.f('ix_message_timestamp'), ['timestamp'], unique=False)
with op.batch_alter_table('user', schema=None) as batch_op:
batch_op.add_column(sa.Column('last_message_read_time', sa.DateTime(), nullable=True))
op.create_index(op.f('ix_message_timestamp'), 'message', ['timestamp'], unique=False)
op.add_column('user', sa.Column('last_message_read_time', sa.DateTime(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('user', schema=None) as batch_op:
batch_op.drop_column('last_message_read_time')
with op.batch_alter_table('notification', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_notification_timestamp'))
batch_op.drop_index(batch_op.f('ix_message_sender_id'))
batch_op.drop_index(batch_op.f('ix_message_recipient_id'))
op.drop_column('user', 'last_message_read_time')
op.drop_index(op.f('ix_message_timestamp'), table_name='message')
op.drop_table('message')
# ### end Alembic commands ###

View File

@ -25,18 +25,14 @@ def upgrade():
sa.Column('password_hash', sa.String(length=128), nullable=True),
sa.PrimaryKeyConstraint('id')
)
with op.batch_alter_table('user', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_user_email'), ['email'], unique=True)
batch_op.create_index(batch_op.f('ix_user_username'), ['username'], unique=True)
op.create_index(op.f('ix_user_email'), 'user', ['email'], unique=True)
op.create_index(op.f('ix_user_username'), 'user', ['username'], unique=True)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('user', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_user_username'))
batch_op.drop_index(batch_op.f('ix_user_email'))
op.drop_index(op.f('ix_user_username'), table_name='user')
op.drop_index(op.f('ix_user_email'), table_name='user')
op.drop_table('user')
# ### end Alembic commands ###

View File

@ -27,20 +27,14 @@ def upgrade():
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
with op.batch_alter_table('notification', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_notification_name'), ['name'], unique=False)
batch_op.create_index(batch_op.f('ix_notification_timestamp'), ['timestamp'], unique=False)
batch_op.create_index(batch_op.f('ix_notification_user_id'), ['user_id'], unique=False)
op.create_index(op.f('ix_notification_name'), 'notification', ['name'], unique=False)
op.create_index(op.f('ix_notification_timestamp'), 'notification', ['timestamp'], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('notification', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_notification_user_id'))
batch_op.drop_index(batch_op.f('ix_notification_timestamp'))
batch_op.drop_index(batch_op.f('ix_notification_name'))
op.drop_index(op.f('ix_notification_timestamp'), table_name='notification')
op.drop_index(op.f('ix_notification_name'), table_name='notification')
op.drop_table('notification')
# ### end Alembic commands ###

View File

@ -1,56 +1,49 @@
aiosmtpd==1.4.4.post2
alembic==1.10.4
async-timeout==4.0.2
atpublic==3.1.1
attrs==23.1.0
Babel==2.12.1
blinker==1.6.2
certifi==2022.12.7
charset-normalizer==3.1.0
click==8.1.3
defusedxml==0.7.1
dnspython==2.3.0
elastic-transport==8.4.0
elasticsearch==8.7.0
email-validator==2.0.0.post2
Flask==2.3.2
flask-babel==3.1.0
Flask-HTTPAuth==4.8.0
Flask-Login==0.6.2
alembic==1.6.5
Babel==2.9.1
blinker==1.4
certifi==2021.5.30
chardet==4.0.0
click==8.0.1
dnspython==2.1.0
dominate==2.6.0
elasticsearch==7.13.3
email-validator==1.1.3
Flask==2.0.1
Flask-Babel==2.0.0
Flask-Bootstrap==3.3.7.1
Flask-HTTPAuth==4.4.0
Flask-Login==0.5.0
Flask-Mail==0.9.1
Flask-Migrate==4.0.4
Flask-Moment==1.0.5
Flask-SQLAlchemy==3.0.3
Flask-WTF==1.1.1
greenlet==2.0.2
httpie==3.2.1
idna==3.4
itsdangerous==2.1.2
Jinja2==3.1.2
Flask-Migrate==3.0.1
Flask-Moment==1.0.1
Flask-SQLAlchemy==2.5.1
Flask-WTF==0.15.1
greenlet==1.1.0
httpie==2.4.0
idna==2.10
itsdangerous==2.0.1
Jinja2==3.0.1
langdetect==1.0.9
Mako==1.2.4
markdown-it-py==2.2.0
MarkupSafe==2.1.2
mdurl==0.1.2
multidict==6.0.4
packaging==23.1
Pygments==2.15.1
PyJWT==2.6.0
Mako==1.1.4
MarkupSafe==2.0.1
Pygments==2.9.0
PyJWT==2.1.0
PySocks==1.7.1
python-dotenv==1.0.0
pytz==2023.3
redis==4.5.4
requests==2.29.0
requests-toolbelt==1.0.0
rich==13.3.5
rq==1.14.0
python-dateutil==2.8.1
python-dotenv==0.18.0
python-editor==1.0.4
pytz==2021.1
redis==3.5.3
requests==2.25.1
requests-toolbelt==0.9.1
rq==1.9.0
six==1.16.0
SQLAlchemy==2.0.10
typing_extensions==4.5.0
urllib3==1.26.15
Werkzeug==2.3.3
WTForms==3.0.1
SQLAlchemy==1.4.20
urllib3==1.26.6
visitor==0.1.3
Werkzeug==2.0.1
WTForms==2.3.3
# requirements for Heroku
#psycopg2-binary==2.9.6
#psycopg2==2.9.1
#gunicorn==20.1.0

View File

@ -42,21 +42,21 @@ class UserModelCase(unittest.TestCase):
db.session.add(u1)
db.session.add(u2)
db.session.commit()
self.assertEqual(u1.following.all(), [])
self.assertEqual(u1.followed.all(), [])
self.assertEqual(u1.followers.all(), [])
u1.follow(u2)
db.session.commit()
self.assertTrue(u1.is_following(u2))
self.assertEqual(u1.following.count(), 1)
self.assertEqual(u1.following.first().username, 'susan')
self.assertEqual(u1.followed.count(), 1)
self.assertEqual(u1.followed.first().username, 'susan')
self.assertEqual(u2.followers.count(), 1)
self.assertEqual(u2.followers.first().username, 'john')
u1.unfollow(u2)
db.session.commit()
self.assertFalse(u1.is_following(u2))
self.assertEqual(u1.following.count(), 0)
self.assertEqual(u1.followed.count(), 0)
self.assertEqual(u2.followers.count(), 0)
def test_follow_posts(self):
@ -87,11 +87,11 @@ class UserModelCase(unittest.TestCase):
u3.follow(u4) # mary follows david
db.session.commit()
# check the following posts of each user
f1 = u1.following_posts().all()
f2 = u2.following_posts().all()
f3 = u3.following_posts().all()
f4 = u4.following_posts().all()
# check the followed posts of each user
f1 = u1.followed_posts().all()
f2 = u2.followed_posts().all()
f3 = u3.followed_posts().all()
f4 = u4.followed_posts().all()
self.assertEqual(f1, [p2, p4, p1])
self.assertEqual(f2, [p2, p3])
self.assertEqual(f3, [p3, p4])