How can I convert string of dateTime to dateTime - python-3.x

takeDate is (Dec. 23, 2020, 8:23 p.m.), I want to change it to DateTime.
Editor Note: Would like to define a URL with variable from which a DateTime object can be created.
urls.py
from django.urls import path
from Reservations import views
urlpatterns = [
path('rent/<takeDate>/<returnDate>/<id>', views.rent, name='rent'),
]
views.py
def rent(request, takeDate, returnDate,id):
print(takeDate)
return render(request, 'reservations/rent.html')

You're better off defining the URL more explicitly to specify the format of the DateTime URL input. Have a look at this, a similar question although using an old version of Django.
Simple
If you define your URL knowing the date format you want to receive, you can easily convert to a datetime:
url_patterns = [
path("rent/<int:take_day>-<int:take_month>-<int:take_year>/<int:return_day>-<int:return_month>-<int:return_year>/<id>/"),
]
Here we have a route that will match numerical dates in the format day-month-year.
Then in your view function, you can grab the arguments like normal and convert them into a DateTime:
from datetime import datetime
def rent(request, take_day, take_month, take_year, return_day, return_month, return_year, id):
takeDateTime = datetime(take_year, take_month, take_day)
returnDateTime = datetime(return_year, return_month, return_day)
# ...
If you want to add in a time, you can keep adding to the URL pattern eg. (format: day-month-year-hour:minute)
"<int:take_day>-<int:take_month>-<int:take_year>-<int:take_hour>:<int:take_minute>"
Advanced
An even better solution, although more advanced is to use a custom path converter, you can read more about them in the Django docs: https://docs.djangoproject.com/en/3.1/topics/http/urls/#registering-custom-path-converters
I won't explain how to implement them here, as the Django docs will do a better job than me if you are interested in this method.

Related

how to correlate using groovy code in jmeter?

1) In my response body comes like json format.
2) Some expected reason ,i have changed that body json to normal text using below code and working expected way
import groovy.json.*
String js = vars.get("cAccountDetails")
def data = new JsonSlurper().parseText(js)
log.info("the value is "+ data)
vars.putObject('data', data)
3) This code meaning converted json to normal text and stored in some variable thats "data"
4) so my response stored in "data" variable .
5) From "data", how can i extract **specific data** using groovy code or some other code?
import java.util.regex.*
import java.util.regex.Matcher
import java.util.regex.Pattern
def matches = (data =~ '{accountDetails=\\[(.*)\\],')
vars.putObject('matches', matches)
The above code using for correlation purpose {"matches" VARIABLE will store extracted value}
but above code is not working ,how can i fix this issue ?
Thanks in advance!!
We cannot help you unless you share your cAccountDetails variable value and indicate what do you need to extract from it.
From the first glance you regular expression should look a little bit different, i.e.
def matches = (data =~ /accountDetails=[(.*)],/)
More information:
Apache Groovy - Find Operator
Apache Groovy - Why and How You Should Use It

(Groovy) Finding all Confluence spaces with a certain user group in it

as the title states, I want to be able to iterate through my Confluence System and find all spaces, in which a certain user group is in.
I am able to find a user group in a single space with the code below, but I can not seem to find an answer how to do this with ALL spaces.
import com.atlassian.confluence.spaces.SpaceManager
import com.atlassian.sal.api.component.ComponentLocator
import com.atlassian.confluence.security.SpacePermissionManager
import com.atlassian.confluence.security.SpacePermission
import com.atlassian.user.GroupManager
import com.atlassian.confluence.core.ContentPermissionManager
import com.atlassian.confluence.internal.security.SpacePermissionContext
def spaceManager = ComponentLocator.getComponent(SpaceManager)
def spacePermissionManager = ComponentLocator.getComponent(SpacePermissionManager)
def groupManager = ComponentLocator.getComponent(GroupManager)
def targetSpace = spaceManager.getSpace("NameOfSpace")
def targetGroup = groupManager.getGroup("UserGroup")
if (spacePermissionManager.getGroupsWithPermissions(targetSpace).contains(targetGroup)) {
//do something (in my case, remove User Group)
}
I tried it with "def allSpaces = spaceManager.getAllSpaces()" and substituted it into the getGroupsWithPermissions() method with no success.
Thanks!
Have you tried SpacePermissionManager#getAllPermissionsForGroup? I haven't tested this with Groovy, but at least in Java, it returns a list of the space permissions attached with the user group.
Not all SpacePermissions will be attached to actual spaces so you will most likely need to loop through the list and filter results where getSpace() is not null.

Flask-sqlalchemy: How serialize objects with custom constructor from existing database?

I'm trying to learn how to create python-based back-ends from some existing data that i have collected. I've come to realize that i definitely want to use sqlalchemy and that flask seems like a good library to go with it. My problem is that even after many hours of reading the sqlalchemy docs and browsing various answers on stackexchange i still don't understand how i can reshape data from an existing table into an object with a completely different structure.
The transformation i want to do is very concrete. I want to go from this structure in my MariaDB table:
Columns: company_name, date, indicators(1...23)
To this json output generated from a serialized class object:
{
"company_name[1]":
{
"indicator_name[1]":
{
"date[1]": "indicator_name[1].value[1]",
"date[2]": "indicator_name[1].value[2]",
"date[3]": "indicator_name[1].value[3]",
"date[4]": "indicator_name[1].value[4]",
"date[5]": "indicator_name[1].value[5]"
},
"indicator_name[2]":
{
"date[1]": "indicator_name[2].value[1]",
"date[2]": "indicator_name[2].value[2]",
"date[3]": "indicator_name[2].value[3]",
"date[4]": "indicator_name[2].value[4]",
"date[5]": "indicator_name[2].value[5]"
},
I found a great tutorial with which i can output the entire table record by record but the structure is not what i want, and i don't think creating the desired structure on the front-end makes sense in this case.
Here is the code that outputs the entire table to json record by record:
from flask import Flask, jsonify
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import PrimaryKeyConstraint
from sqlalchemy import orm
from sqlalchemy import select, func
from sqlalchemy import Column, Integer, String, ForeignKey
from flask_marshmallow import Marshmallow
import decimal
import flask.json
class MyJSONEncoder(flask.json.JSONEncoder): # Enables decimal queries for the API
def default(self, obj):
if isinstance(obj, decimal.Decimal):
# Convert decimal instances to strings.
return str(obj)
return super(MyJSONEncoder, self).default(obj)
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://USER:PASS#localhost:3306/kl_balance_sheets'
app.json_encoder = MyJSONEncoder
db = SQLAlchemy(app)
ma = Marshmallow(app)
# Bind declarative base to engine
db.Model.metadata.reflect(db.engine)
class CompanyData(db.Model):
__table__ = db.Model.metadata.tables['kl_balance_sheets']
class CompanyDataSchema(ma.ModelSchema):
class Meta:
model = CompanyData
#app.route('/')
def index():
company_data = CompanyData.query.all()
company_data_schema = CompanyDataSchema(many=True)
output = company_data_schema.dump(company_data).data
return jsonify({'company_data' : output})
if __name__ == '__main__':
app.run(debug=True)
My main question i guess is: How do i edit this code to produce the desired json?
What i think i should do is to create a custom constructor and then feed that into the index function but i can't figure out how to concretely do that. The two options i've come across are:
#orm.reconstructor
def init_on_load(self):
#do custom stuff
or:
class Foo(db.Model):
# ...
def __init__(**kwargs):
super(Foo, self).__init__(**kwargs)
# do custom stuff
To me this seems like a basic operation any flask-marshmallow user would be doing regularly. Could someone please explain how sql data is normally inserted into an object with a new structure and then serialized? In my case, do i need to change things mainly on the metadata, object or marshmallow level? I'm surprised i can't find some good examples of this.

Add a unique timestamp to a text using Selenium and Python3

Quick question which I thought I'd find a simple answer to but so far, no luck.
I'm creating automation to go through sign up forms and for this I ideally need to send some unique text. I was thinking of something like name+timestamp (as do-able on Ghost Inspector).
Currently I'm okay just writing a quick unique name each time in my code (using send.keys('')), just looking to see if there's a way to cut this small chore out really.
To add a unique timestamp to a text you can use Python's strftime() method from time module as follows:
Code Block:
from selenium import webdriver
from time import gmtime, strftime
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_argument('disable-infobars')
driver=webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get("http://www.google.com")
driver.find_element_by_name("q").send_keys("James Stott{}".format(strftime("%Y-%m-%d %H:%M:%S", gmtime())))
Browser Snapshot:
You can use this code to generate random Strings which you can send it to sendKeys("") command.
import string
import random
def random_string(length):
return ''.join(random.choice(string.ascii_letters) for m in range(length))
print random_string(10)
print random_string(5)
If you want to use UUID :
import uuid
id = uuid.uuid1()
print (id.hex) // for hex representation
print (id.int)
If you want to use timestamp, then you can use this code :
import datetime
print('Date now: %s' % datetime.datetime.now())
here is the reference link : datetime python

What's get_products() missing 1 required positional argument: 'self'

I am trying to program for a friend of mine for fun and practice to make myself better in Python 3.6.3, I don't really understand why I got this error.
TypeError: get_products() missing 1 required positional argument: 'self'
I have done some research, it says I should initialize the object, which I did, but it is still giving me this error. Can anyone tell me where I did wrong? Or is there any better ways to do it?
from datetime import datetime, timedelta
from time import sleep
from gdax.public_client import PublicClient
# import pandas
import requests
class MyGdaxHistoricalData(object):
"""class for fetch candle data for a given currency pair"""
def __init__(self):
print([productList['id'] for productList in PublicClient.get_products()])
# self.pair = input("""\nEnter your product name separated by a comma.
self.pair = [i for i in input("Enter: ").split(",")]
self.uri = 'https://api.gdax.com/products/{pair}/candles'.format(pair = self.pair)
#staticmethod
def dataToIso8681(data):
"""convert a data time object to the ISO-8681 format
Args:
date(datetime): The date to be converted
Return:
string: The ISO-8681 formated date
"""
return 0
if __name__ == "__main__":
import gdax
MyData = MyGdaxHistoricalData()
# MyData = MyGdaxHistoricalData(input("""\nEnter your product name separated by a comma.
# print(MyData.pair)
Possibly you missed to create object of PublicClient. Try PublicClient().get_products()
Edited:
why I need the object of PublicClient?
Simple thumb rule of OOP's, if you wanna use some property(attribute) or behavior(method) of class, you need a object of that class. Else you need to make it static, use #staticmethod decorator in python.

Resources