Tag Archives: back-end

[Solved] django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.Did you install mysqlclie

Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/home/delta/.local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 15, in <module>
    import MySQLdb as Database
ModuleNotFoundError: No module named 'MySQLdb'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "/home/delta/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/home/delta/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run
    autoreload.raise_last_exception()
  File "/home/delta/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception
    raise _exception[1]
  File "/home/delta/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
    autoreload.check_errors(django.setup)()
  File "/home/delta/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/home/delta/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/delta/.local/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate
    app_config.import_models()
  File "/home/delta/.local/lib/python3.6/site-packages/django/apps/config.py", line 301, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/delta/.local/lib/python3.6/site-packages/django/contrib/auth/models.py", line 3, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "/home/delta/.local/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 48, in <module>
    class AbstractBaseUser(models.Model):
  File "/home/delta/.local/lib/python3.6/site-packages/django/db/models/base.py", line 122, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "/home/delta/.local/lib/python3.6/site-packages/django/db/models/base.py", line 326, in add_to_class
    value.contribute_to_class(cls, name)
  File "/home/delta/.local/lib/python3.6/site-packages/django/db/models/options.py", line 207, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "/home/delta/.local/lib/python3.6/site-packages/django/utils/connection.py", line 15, in __getattr__
    return getattr(self._connections[self._alias], item)
  File "/home/delta/.local/lib/python3.6/site-packages/django/utils/connection.py", line 62, in __getitem__
    conn = self.create_connection(alias)
  File "/home/delta/.local/lib/python3.6/site-packages/django/db/utils.py", line 204, in create_connection
    backend = load_backend(db['ENGINE'])
  File "/home/delta/.local/lib/python3.6/site-packages/django/db/utils.py", line 111, in load_backend
    return import_module('%s.base' % backend_name)
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "/home/delta/.local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 20, in <module>
    ) from err
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install mysqlclient?

One of the reasons for this error when starting the Django project is:

Because pymysql is not installed or not configured,

Pymysql is not installed. It needs to be built into the environment and executed

import pymysql
pymysql.install_as_MySQLdb()

Done!

[Solved] Spring upload file Error: Multipartfile Transferto() reported an error FileNotFoundException

When uploading files, use multipartfile Transferto() saves the file to the local path:

report errors:

java.io.IOException: java.io.FileNotFoundException: C:\Users\XXXXX\AppData\Local\Temp\tomcat. 8350081478984499756.8080\work\Tomcat\localhost\ROOT\app\file\xxxx. Xlsx (the system cannot find the specified path.)

    @Override
    public String store(MultipartFile file, String fileName) throws IOException {

        String destPath "/app/file/";
        File filePath = new File(destPath);
        File dest = new File(filePath, fileName);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        try {
            file.transferTo(dest);
            log.info("file save success");
        } catch (IOException e) {
            log.error("File upload Error: ", e);
            throw e;
        }
        return dest.getCanonicalPath();
    }

Cause analysis:

file. When the transferto method is called, it is judged that if it is a relative path, the temp directory is used as the parent directory
so it is saved in the temporary work directory of Tomcat.

Solution:

Use absolute path: filepath.getAbsolutePath()

    @Override
    public String store(MultipartFile file, String fileName) throws IOException {

        String destPath "/app/file/";
        File filePath = new File(destPath);
        
        // Convert to absolute path
        File dest = new File(filePath.getAbsolutePath(), fileName);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        try {
            file.transferTo(dest);
            log.info("file save success");
        } catch (IOException e) {
            log.error("File upload Error: ", e);
            throw e;
        }
        return dest.getCanonicalPath();
    }

Supplement:

You can also file Getbytes() gets the byte array, or file Getinputstream() performs stream data operation and writes it to disk.

Access to uploaded files

spring:
	resources:
    	static-locations: file:/app/file/  #Access external system resources and map the files in this directory to the system

or

import java.io.File;
import java.util.concurrent.TimeUnit;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String absolutePath = new File("/app/file/").getAbsolutePath();
        
        registry.addResourceHandler("/upload/**") // External Access Addresses
                .addResourceLocations("file:" + absolutePath)// SpringBoot needs to add the file protocol prefix
                .setCacheControl(CacheControl.maxAge(30, TimeUnit.MINUTES));// set the browser cache
    }
}

The Java class generated by protocol reports an error: cannot access

The Java class generated by protocol reports an error:

The generated template class reported an error. It was said on the Internet that the version was wrong, but I was sure that the version used was correct. Later, it was checked that a proto was introduced into the command_Path causes the generated template class to report an error

Error command:

protoc --proto_path=D:\000\hadoop-2.7.2-src\hadoop-yarn-project\hadoop-yarn\hadoop-yarn-api\src\main\proto\ --proto_path=D:\000\hadoop-2.7.2-src\hadoop-common-project\hadoop-common\src\main\proto\ --proto_path=.\ --java_out=.\ .\*.proto

Change to the following command:

protoc --proto_path=D:\000\hadoop-2.7.2-src\hadoop-common-project\hadoop-common\src\main\proto\  --proto_path=.\ --java_out=.\ .\*.proto

One less — proto_Path, and then the problem is solved

How to Solve Java Runtime (class file version 53.0)ERROR

libs/granite/ui/components/shell/header/user/User has been compiled by a more recent version of the Java Runtime (class file version 53.0), this version of the Java Runtime only recognizes class file versions up to 52.0

Specific corresponding version:

JDK 1.1 = 45
JDK 1.2 = 46
JDK 1.3 = 47
JDK 1.4 = 48
Java SE 5.0 = 49
Java SE 6.0 = 50
Java SE 7 = 51
Java SE 8 = 52
Java SE 9 = 53
Java 10 = 54
Java 11 = 55
Java 12 = 56
…

 

So the question is, how to replace the version?
First of all, the easiest way is to check whether java has been installed through the command: java -version
View the java package of yum source: yum list java*
Install java108jdk software: yum -y install java-1.8.0-openjdk****
Verify that the installation is successful, check the java version: java -version

[Solved] FLask Error: AttributeError: ‘Blueprint‘ object has no attribute ‘register_blueprint‘

Recently, a flash was deployed on alicloud, and an error was reported during startup

AttributeError: ‘Blueprint’ object has no attribute ‘register_blueprint’

I checked the location. There was an error below!

admin_bp = Blueprint('admin',__name__)
admin_bp.register_blueprint(activity_bp,url_prefix='/activity')

First of all, there is no problem running locally. When uploading to the server (CentOS 7, py39), an error is reported. Maybe it is because it is not standardized, but it should also be reported on the window. I don’t understand.

Solution:

Blueprint cannot call Method of register_blueprint(), register_Blueprint() is handed over to the app, and this line is moved to the place where the app is referenced

app.register_blueprint(activity_bp,url_prefix='/activity')

This should be no problem!

[Solved] Annotation Customize Error: ElementType cannot be resolved to a variable

In the development process, you may use custom annotations (this article uses custom annotations when using JWT) to report an error:

ElementType cannot be resolved to a variable

Manually import packages:

import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;

Perfect solution

[Solved] activiti integrate error: GlobalAuthenticationConfigurerAdapter.class does not exist

@EnableSwagger2
@SpringBootApplication(scanBasePackages = {"cn.com.ten"} ,exclude = {org.activiti.spring.boot.SecurityAutoConfiguration.class})
@MapperScan(basePackages = {"cn.com.ten.**.dao"})
public class SystemEtlApplication {

    public static void main(String[] args) {
        SpringApplication.run(SystemEtlApplication.class, args);
    }

}

Springboot integration activiti reported an error

Caused by: java.io.FileNotFoundException: class path resource [org/springframework/security/config/annotation/authentication/configurers/GlobalAuthenticationConfigurerAdapter.class]
cannot be opened because it does not exist

 

Solution:

Add springbootapplication on the startup class

exclude = {org.activiti.spring.boot.SecurityAutoConfiguration.class}

How to Solve Log4j 2.5 upgrade to 2.15 error

Question

Log4j2 is used in the project. Due to the use of global asynchronous log printing, it is also necessary to introduce the dependency of disruptor. The version dependency of log4j2 and disruptor used last is as follows:

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.11.1</version>
</dependency>
<!-- log4j2 AsyncLogger need disruptor-->
<dependency>
    <groupId>com.lmax</groupId>
    <artifactId>disruptor</artifactId>
    <version>3.2.0</version>
</dependency>

At the beginning of the project (before the logger of log4j2 is used for the first time), enable global asynchronous log printing through code:

// use asyncLogger for log4j2 framework
System.setProperty("Log4jContextSelector", "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");

However, the errors reported after starting the project are as follows:

java.lang.NoSuchMethodError: com.lmax.disruptor.dsl.Disruptor.<init>(Lcom/lmax/disruptor/EventFactory;ILjava/util/concurrent/ThreadFactory;Lcom/lmax/disruptor/dsl/ProducerType;Lcom/lmax/disruptor/WaitStrategy;)V
        at org.apache.logging.log4j.core.async.AsyncLoggerDisruptor.start(AsyncLoggerDisruptor.java:97)
        at org.apache.logging.log4j.core.async.AsyncLoggerContext.start(AsyncLoggerContext.java:75)
	at .......

Solution:

The problem is caused by the lower version of the disruptor. Just change the version to the newer version:

<dependency>
    <groupId>com.lmax</groupId>
    <artifactId>disruptor</artifactId>
    <version>3.4.2</version>
</dependency>

JUnit tests mybatis-plus error: null pointer [How to Solve]

Question:

Because the project uses microservices, a service is created in the microservices to write mybatis plus in order to save trouble. However, a null pointer error occurs when JUnit tests after writing according to the official website documents.

Test class of official website document:

An error occurred:

The value of usermapper was found to be empty

By checking the data, it is found that this is because ordinary classes can’t use springbeans, so ordinary test classes can’t get beans, so they report null pointers. Therefore, we need to make the test class get the bean.

Solution:

Add test dependency:

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

And add notes on the test class:

@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)

solve the problem

Java error: java.lang.NoSuchMethodError

The Java runtime reports an error
the postman test reports an error of 500. The exception information is displayed as follows:


reason: first, check whether there is a method of this attribute in the previous class. If so, it is mostly a problem of dependency conflict. In general, it may be that classes with the same package name and class name are introduced. The order in which dependencies are introduced in the POM file of the project is inconsistent, resulting in the use of other people’s classes with the same package and the same name, and there is no corresponding entity class attribute paramscheckresult. An error will be reported in the result. Query the full path name of the class you introduced.

 

Methods:

ProtectionDomain pd = Response.class.getProtectionDomain();
CodeSource cs = pd.getCodeSource();
System.out.println(cs.getLocation().toString());

Print result: the full path name of the imported class will be displayed