models.py
from mongoengine import Document, fields
class Tool(Document):
Fruit = fields.StringField(required=True)
District = fields.StringField(required=True)
Area = fields.StringField(required=True)
Farmer = fields.StringField(required=True)
Serializers.py file
from rest_framework import serializers
from rest_framework_mongoengine.serializers import DocumentSerializer
from models import Tool
class ToolSerializer(DocumentSerializer):
class Meta:
model = Tool
views.py file
from django.template.response import TemplateResponse
from rest_framework_mongoengine.viewsets import ModelViewSet as MongoModelViewSet
from app.serializers import *
def index_view(request):
context = {}
return TemplateResponse(request, 'index.html', context)
class ToolViewSet(MongoModelViewSet):
lookup_field = 'Fruit'
serializer_class = ToolSerializer
def get_queryset(self):
return Tool.objects.all()
So,I want to create queries like http://127.0.0.1:8000/api/tool/?Fruit=Banana gives me all data for fruit banana only. Also, http://127.0.0.1:8000/api/tool/?District=Pune gives me data for Pune district only .
Unfortunately, I haven't tried this solution myself yet, but AFAIK, in pure DRF with SQL database you'd use Django-Filters package for this.
There's an analogue of it for DRF-ME, called drf-mongo-filters, written by Maxim Vasiliev, co-author of DRF-ME. It contains a decent set of tests, you could use for inspiration.
Basically, you say something like:
from rest_framework.test import APIRequestFactory
from rest_framework.generics import ListAPIView
from mongoengine import Document, fields
from drf_mongo_filters.filtersets import filters, Filterset, ModelFilterset
from drf_mongo_filters.backend import MongoFilterBackend
class TestFilter(Filterset):
foo = filters.CharFilter()
class TestView(ListAPIView):
filter_backends = (MongoFilterBackend,)
filter_class = TestFilter
serializer_class = mock.Mock()
queryset = mock.Mock()
TestView.as_view()(APIRequestFactory().get("/?foo=Foo"))
TestView.queryset.filter.assert_called_once_with(foo="Foo")
Haven't tried doing the same with ViewSets, but as they inherit from GenericView, I guess, they should respect filter_class and filter_backends parameters, too.
Related
I'm a bit struggling with the JavaScript classes (CommonJS).
I've got a class in a javascript 'module' which I can import to another js file using:
DucoMaster.js:
class DucoMaster {
constructor(node){
this.node = node;
}
}
module.exports = {DucoMaster}
DucoModules.js:
const {DucoMaster} = require("./DucoMaster");
...
let test = new DucoMaster;
console.log(test);
It builds and printing the test works, it prints the object as defined as class in DucoMaster.
Now I would like to import the module and use it to extend another class like:
'class DucoMaster extends ParentClass' within DucoModules.js
Is this possible with DucoModules.js?
Best regards,
I need to convert an object of Map<String,String> with keys like "some_att_name" to class object fields like someAttName.
I couldn't find an easy way to do this.
MapStruct does support this type of mapping (From Map to object) since v1.5.0.Beta1 as stated here.
What I want should look something like this (similar to how JSON converters work):
#Mapper
public interface MapToObjectMapper {
MapToObjectMapper INSTANCE = Mappers.getMapper(MapToObjectMapper.class);
#Mapping(strategy = SnakeCaseToCamelCaseStrategy.class)
MyObject toMyObject(Map<String,String> map);
}
You'll have to translate the keys by yourself, but that's not that hard. Here is how I do it:
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import java.util.Collections;
import java.util.Map;
import java.util.regex.Pattern;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toMap;
#Mapper
public interface MapToObjectMapper {
MapToObjectMapper INSTANCE = Mappers.getMapper(MapToObjectMapper.class);
private static String snakeToCamel(String snakeCaseString) {
// You can use Guava, Apache Commons, write it yourself or just use this one
// Credits to https://stackoverflow.com/a/67605103/4494577
return Pattern.compile("_([a-z])")
.matcher(snakeCaseString)
.replaceAll(m -> m.group(1).toUpperCase());
}
MyObject toMyObject(Map<String, String> map);
default MyObject toMyObjectFromSnakeCaseMap(Map<String, String> snakeKeyPropertyMap) {
return toMyObject(snakeKeyPropertyMap.entrySet().stream()
.collect(collectingAndThen(
toMap(s -> snakeToCamel(s.getKey()), Map.Entry::getValue),
Collections::unmodifiableMap)));
}
}
Full example: https://github.com/jannis-baratheon/stackoverflow--mapstruct-snake-case-map-mapping/
Looking at the docs I can't see a 1 step mapping. I think referring to From snake_case to camelCase in Java for converting your Map's keys to camelCase and then going for a mapper without #Mapping annotations might be your best chance.
I'm using mongodb as database and trying to extend the django's inbuilt user model.
here's the error I'm getting:
django.core.exceptions.ValidationError: ['Field "auth.User.id" of model container:"<class \'django.contrib.auth.models.User\'>" cannot be of type "<class \'django.db.models.fields.AutoField\'>"']
Here's my models.py:
from djongo import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.EmbeddedField(model_container=User)
mobile = models.PositiveIntegerField()
address = models.CharField(max_length=200)
pincode = models.PositiveIntegerField()
Using EmbeddedField is not a good idea, because it will duplicate user data in the database. You will have some user in the Users collection and the same data will be embedded in the Profile collection elements.
Just keep the user id in the model and query separately:
class Profile(models.Model):
user_id = models.CharField() #or models.TextField()
mobile = models.PositiveIntegerField()
address = models.CharField(max_length=200)
pincode = models.PositiveIntegerField()
It is simple as defined in the documentation.
So, first, use djongo models as the model_container, and I suppose the User model is the Django model, not the djongo model.
And the second thing, make your model_cotainer model abstract by defining in the Meta class as given below.
from djongo import models
class Blog(models.Model):
name = models.CharField(max_length=100)
class Meta:
abstract = True
class Entry(models.Model):
blog = models.EmbeddedField(
model_container=Blog
)
headline = models.CharField(max_length=255)
Ref: https://www.djongomapper.com/get-started/#embeddedfield
I need to display the title and name of all child and grand child pages from given path in JSON format. Please provide the implementation.
First You have to try something yourself, then you call for help, not the complete solution!anyway there are couple of solution down there.
According to Adobe here you can implement page information in JSON format:
package com.adobe.example;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.Service;
import org.apache.felix.scr.annotations.Reference;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageInfoProvider;
#Component(metatype = false)
#Properties({
#Property(name="service.description", value="Returns the public URL of a resource.")
})
#Service
public class PageUrlInfoProvider implements PageInfoProvider {
#Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY)
private com.day.cq.commons.Externalizer externalizer;
private String fetchExternalUrl(ResourceResolver rr, String path) {
return externalizer.publishLink(rr, path);
}
public void updatePageInfo(SlingHttpServletRequest request, JSONObject info, Resource resource)
throws JSONException {
Page page = resource.adaptTo(Page.class);
JSONObject urlinfo = new JSONObject();
urlinfo.put("publishURL", fetchExternalUrl(null,page.getPath()));
info.put("URLs",urlinfo);
}
}
Or you may try this Page for solution
Please refer to below link which may be useful:
http://www.nateyolles.com/blog/2015/12/converting-aem-sling-resources-to-json.
Apart from the above solution you also use recursive level to get the data in the JSON format for example /content/we-retail/language-masters/en.{placeholder}.json
replace the placeholder with the level of nodes you want to print and return back the JSON wherever needed.
To know more about the rendering data in different formats,
Refer: https://sling.apache.org/documentation/bundles/rendering-content-default-get-servlets.html
I have 2 different test cases which have different URL's.
Common thing between two URL's is the unique ID. I have captured the URL of one test case and split the URL of that test case and stored the ID in a variable. I made that variable a global variable and tried to use it in 2nd test case.
Now, I want to use that ID obtained from 1st test case in 2nd test case.
I got the error below:
**Test Case FAILED because (of) org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'ba0eed2c-cba8-11e8-86a5-02e9072e0d95' with class 'java.lang.String' to class 'internal.GlobalVariable'**
**Code for Test Case A is as follows:**
import static com.kms.katalon.core.checkpoint.CheckpointFactory.findCheckpoint
import static com.kms.katalon.core.testcase.TestCaseFactory.findTestCase
import static com.kms.katalon.core.testdata.TestDataFactory.findTestData
import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject
import com.kms.katalon.core.checkpoint.Checkpoint as Checkpoint
import com.kms.katalon.core.checkpoint.CheckpointFactory as CheckpointFactory
import com.kms.katalon.core.mobile.keyword.MobileBuiltInKeywords as MobileBuiltInKeywords
import com.kms.katalon.core.mobile.keyword.MobileBuiltInKeywords as Mobile
import com.kms.katalon.core.model.FailureHandling as FailureHandling
import com.kms.katalon.core.testcase.TestCase as TestCase
import com.kms.katalon.core.testcase.TestCaseFactory as TestCaseFactory
import com.kms.katalon.core.testdata.TestData as TestData
import com.kms.katalon.core.testdata.TestDataFactory as TestDataFactory
import com.kms.katalon.core.testobject.ObjectRepository as ObjectRepository
import com.kms.katalon.core.testobject.TestObject as TestObject
import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WSBuiltInKeywords
import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WS
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUiBuiltInKeywords
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
import internal.GlobalVariable as GlobalVariable
import org.openqa.selenium.Keys as Keys
WebUI.click(findTestObject('PO_ID_Details_Passport/label_Select Document Type'))
WebUI.click(findTestObject('PO_ID_Details_Passport/li_Passport'))
WebUI.setText(findTestObject('PO_ID_Details_Passport/input_PO_PASSPORT_NUMBER'), 'Test123456')
WebUI.setText(findTestObject('PO_ID_Details_Passport/input'), '25')
WebUI.setText(findTestObject('PO_ID_Details_Passport/input_1'), '05')
WebUI.setText(findTestObject('PO_ID_Details_Passport/input_2'), '2025')
// Capture the current URL and split the URL to get the unique ID.
String url = WebUI.getUrl()
String getQueryString = url.split("\\?")[1]
String[] getFields = getQueryString.split("&")
Map<String, String> fieldValueMap = new HashMap<String, String>()
for(String field : getFields) {
fieldValueMap.put(field.split("=")[0], field.split("=")[1])
}
println fieldValueMap.get("JID")
GlobalVariable JourneyID=fieldValueMap.get("JID")
//return JourneyID
Thread.sleep(5000)
WebUI.click(findTestObject('PO_ID_Details_Passport/Upload_File'))
Thread.sleep(3000)
//Sample path. Change it to your saved location of autoIT script
Runtime.getRuntime().exec('ABC')
Thread.sleep(5000)
WebUI.click(findTestObject('PO_ID_Details_Passport/i'))
]
How can I use the value of JourneyID in different test case?
you can use A global variable to store value as shown below.
GlobalVariable.JourneyID=fieldValueMap.get("JID")
But before using this variable, create a Global Variable named 'JourneyID' and pass some static value to it.
Now you can use it in other test cases.
Hope this will help you.