Managing time from a flask backend server for different countries - date

I have been working on a web application, the backend is built with flask, frontend with Reactjs, after hosting it, I realized that the time that I was storing at the backend was saved reflecting the location of the server where I hosted the backend. so my question goes.
How do I save date and time at the level of the flask backend, and then convert it in the frontend using the user's location on the browser to reflect the local time of the user?
Would appreciate a kind solution.

If you want to do the conversion at the server level i.e. flask, then you could try something like this, where the client when firing a request to server specifies the timezone it is in(example US/Pacific ) and server can respond the details accordingly.
import os
from datetime import datetime
import pytz
from flask import Flask, request, jsonify
app = Flask(__name__)
#app.route('/time')
def time():
#Default sever level date and time
current_server_time = datetime.now()
if 'timezone' in request.args:
tzinfo = pytz.timezone(request.args['timezone'])
#Converting date and time based on timeone input from client
current_client_time = current_server_time.astimezone(tzinfo)
return jsonify({"time":current_client_time})
return jsonify({"time":current_server_time})
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0', port=8001)
You can try it by accessing http://localhost:8001/time?timezone=US/Pacific
You will obviously have to add in validation related to timezone received from the client.
I'm sure you can do conversion at reactjs level as well, as long as the server response specifies timezone.

Related

Extract data from Get requests in python FLASK

I have a front on which forms for data entry, I enter data there and they go to the backend, but I need to intercept them and write them to the database. I have a script that writes data to a database, but I don't understand how to intercept the data. I am using the Flask framework. Help me please!
#app.route('/')
def main_page():
return "<html><head></head><body>A RESTful API in Flask using.</a>.</body></html>"
#app.route('/api/v1/reports/', methods='GET'):

Django changes datetime automatically

I have django project and one separate service.
In django timezone is UTC+3 and in separate service I have written pure sql codes
like below
INSERT INTO Table(something,something,datetime) VALUES(%s,%s,%s)
as a datetime field if I send 2021-04-28 01:00:00, django will save it 2021-04-28 04:00:00,
3 hours more. How can I implement db to store exactly what I send there.

Flask SQl-Alchemy multiple DB transactions in single request

I am trying to make a single route Flask web app in which the user submits a URL to the client, some data from the URL is extracted at the server-side and appended to a Postgres DB. Next, further processing is done on the data extracted from the URL and the data entry of the URL in the DB is updated. All this processing is done as background tasks using celery. The work flow looks something like this:
#app.route
def app_route(url):
chain(task1(url) | task2(url))
#celery.task
def task1(url):
out1 = some_long_task(url)
append url,out1 to db
#celery.task
def task2(url):
out2 = some_other_long_task(url)
update url row in db with out2
The reason we do this is that, these two tasks are long tasks, and the user should be able to see the status of the task in the client. Hence, we update the out1 in the DB first so the user can know the status and then with out2 so the user can know the final status. At any point, the user can visit the home page which displays the URLs in the DB currently with their data.
This throws me an error: psycopg2.OperationalError) SSL error: decryption failed or bad record mac
The url with out1 is appended to the DB correctly without issue. But the second time when we try to update the row we appended in the previous task, it throws the above error. I am guessing flask sqlalchemy only allows a single session to a DB in one request, hence the error. What can I do to solve this issue?
I solved the error. Switched from flask-sqlalchemy to sqlalchemy to connect to the database since it offers more visibility. One should dispose the engine object by calling engine.dispose() after connecting the app to the database and the error disappears.

Flask -- Reloading database which was loaded before first request

I have an API run on flask which is connected to MongoDB and it uses this DB for reading only.
I connect to db before first request:
#app.before_first_request
def load_dicti():
c = MongoClient('mongodb://' + app.config['MONGO_DSN'], connect=False)
db = c.my_name
app.first, app.second = dictionary_compilation(db.my_base, another_dictionary)
However, this mongodb may be updated from time to time. My API doesn't know about it because this db was already loaded before first request.
What's the most efficient way to cope with it? I'd be grateful for explanations and code examples.
I don't quite figure out what you are going to do, but Application Context may be best practice. Just like demo in Flask docs, you could do:
def get_db():
"""Opens a new database connection if there is none yet for the
current application context.
"""
if not hasattr(g, 'db'):
c = MongoClient('mongodb://' + app.config['MONGO_DSN'], connect=False)
g.db = c.my_name
return g.db
Then, you could use get_db() directly in your view function, mongdb will be conntected once only when there is no db attr in g.
If your connection is not that stable that you need to change it everytime, you could connect every request or every session.

saving a clientside date as UTC date object into Mongo

I am trying to save a date into meteor mongodb my challenge is as follows:
1) if i use new Date() it creates a date object in mongo DB however it saves the time as local time as javascript Date() this always comes with a timezone +0x:hours based on browser local timezone. When i retrieve this it causes havoc as i am assuming everything in my db is UTC.
2) I want to use moment js library which is great because it can represent dates in UTC properly but my challenge is how do i get mongo db to accept a moment time? The minute i use moment.format() it saves it as a string!
So how can i send a date to a mongodb insert command with a date object that is in UTC? string just dont work :(
Any help would be appreciated.
Thanks
I think everything you need to know about both of these questions can be found here and here.
TLDR:
If you directly insert/update from the client you will store a timestamp based on the user's clock. It will still be stored as UTC, but you may or may not want to trust that the time is correct. I strongly suggest using a method for any db modifications which involve time so that the server's version of time will always be used.
Moment objects are not serializable to a format compatible with mongodb. Use a date object and format it on the client.
The problem with saving dates on the client is that each client can have a different time zone, or even wrong time set. Thus the only solution is to have the date set on the server. Using a method for each insert / update is not an elegant solution.
A common practice is to modify the document inside allow or deny callback:
Messages.allow({
insert: function(userId, doc) {
...
doc.timestamp = new Date();
return true;
},
});
That way you ensure all documents have a compatible timestamp, and you can use usual db methods on the client.
The Meteor community recently started an extensive document about how to use dates and times. You'll find a lot of useful information there, in addition to David Weldon's links:
https://meteor.hackpad.com/Meteor-Cookbook-Using-Dates-and-Times-qSQCGFc06gH
However, in particular I recommend using https://github.com/mizzao/meteor-timesync when security is not a concern. It allows you to client-locally obtain an accurate server time even if the client's clock is way off, without a round-trip to the server. This can be useful for all kinds of reasons - in my apps, I universally just use server-relative time and don't care about what the client's time is at all.